I have some trade data like this
{
"_id" : 1498290900.0,
"trade" : {
"type" : "Modify",
"data" : {
"type" : "bid",
"rate" : "0.00658714",
"amount" : "3.82354427"
},
"date" : 1498290930291.0,
"name" : "TLX"
}
},{
"_id" : 1498290900.0,
"trade" : {
"type" : "Modify",
"data" : {
"type" : "ask",
"rate" : "0.00658714",
"amount" : "3.82354427"
},
"date" : 1498290930291.0,
"name" : "TLX"
}
},{
"_id" : 1498290900.0,
"trade" : {
"type" : "Remove",
"data" : {
"type" : "ask",
"rate" : "0.00680891"
},
"date" : 1498290931349.0,
"name" : "TLX"
}
}
These come from $rewind hence the _id being same. Want i want to do next is group them on _id so i try
{
$group: {
_id: {_id: "$_id", name: "$trade.type",dtype: "$trade.data.type"},
count : {$sum: 1}
},
},{$project: { _id: "$_id._id", type: "$_id.name", count: 1, dtype: "$_id.dtype" } },
{
$group: {
_id: "$_id",
results: { $push : "$$ROOT" }
}
}
Which is quite good, give me the below
{
"_id" : 1498276800.0,
"results" : [
{
"count" : 16.0,
"_id" : 1498276800.0,
"type" : "Modify",
"dtype" : "bid"
},
{
"count" : 15.0,
"_id" : 1498276800.0,
"type" : "Remove",
"dtype" : "bid"
},
{
"count" : 3.0,
"_id" : 1498276800.0,
"type" : "Remove",
"dtype" : "ask"
},
{
"count" : 1.0,
"_id" : 1498276800.0,
"type" : "Modify",
"dtype" : "ask"
}
]
}
But i was trying to make the output more like this
{
"_id" : 1498276800.0,
"Modify": {
"bid":{
"count": 16.0
},
"ask": {
"count": 1.0
}
},
"Remove": {
"bid":{
"count": 15.0
},
"ask": {
"count": 3.0
}
}
}
But no amount of playing with $projections has got me close.
Can anyone point me in the right direction please?
thanks.
UPDATE
Excluding last pipeline stage, this is example documents with nice bid/ask per type ready to be grouped by _id.
{
"_id" : {
"_id" : 1498276800.0,
"type" : "orderBookRemove"
},
"results" : [
{
"k" : "bid",
"v" : {
"count" : 15.0
}
},
{
"k" : "ask",
"v" : {
"count" : 3.0
}
}
]
},
{
"_id" : {
"_id" : 1498276800.0,
"type" : "orderBookModify"
},
"results" : [
{
"k" : "bid",
"v" : {
"count" : 16.0
}
},
{
"k" : "ask",
"v" : {
"count" : 1.0
}
}
]
}
When last part of pipeline is applied i.e
{ "$group": {
"_id": "$_id._id",
"results": {
"$push": {
"k": "$_id.type",
"v": "$results"
}
}
}}
I get this, only first 'bid' element of results array. 2nd item 'ask' goes AWOL ?
{
"_id" : 1498280700.0,
"results" : [
{
"k" : "orderBookRemove",
"v" : [
{
"k" : "bid",
"v" : {
"count" : 9.0
}
}
]
},
{
"k" : "orderBookModify",
"v" : [
{
"k" : "bid",
"v" : {
"count" : 6.0
}
}
]
}
]
}