I am relatively new to Mongo, and trying to figure out how to complete this query. I'm using mongoose, in node.js. I want to get the sums of sell.amount, and buy.amount, from this document with a nested array of objects. The trades array is large, and I want to limit it to the first (from 0 ) n number of objects. I want to be able to get returned something like:
{buy.totalAmount, buy.tradesCount},{sell.totalAmount, sell.tradesCount},
as a sum of the number of elements selected by $limit
I figure I must be close, but so far I cannot figure out how to make this work.
My Query:
tradePair.aggregate(
{$match: {pair:"STOCK"}},
{$unwind:"$trades"},
{$limit: 20},
{$group : { _id : '$trades.buy',
count : {$sum : 1},
totalAmount: { $sum: '$trades.buy.amount' }
}},
function(err,result){
return result
}
)
My Database Document, showing only 2 trade array elements..of many...
{
"_id" : ObjectId("58fa86c81cdd7b2375cdd4cc"),
"pair" : "STOCK",
"trades" : [
{
"sell" : {
"trades" : 1,
"total" : 0.13309789,
"amount" : 24.80139,
"rate" : 0.00536655
},
"buy" : {
"trades" : 0,
"total" : 0,
"amount" : 0,
"rate" : 0
},
"_id" : ObjectId("58fa87290567372b4035d16f"),
"endTradeId" : 41306,
"startTradeId" : 41306,
"dateEnd" : ISODate("2017-04-21T21:37:39.000Z"),
"dateStart" : ISODate("2017-04-21T21:37:39.000Z")
},
{
"sell" : {
"trades" : 2,
"total" : 1.23879614,
"amount" : 230.83659924,
"rate" : 0.00536655
},
"buy" : {
"trades" : 0,
"total" : 0,
"amount" : 0,
"rate" : 0
},
"_id" : ObjectId("58fa87290567372b4035d16e"),
"endTradeId" : 41305,
"startTradeId" : 41304,
"dateEnd" : ISODate("2017-04-21T21:35:28.000Z"),
"dateStart" : ISODate("2017-04-21T21:35:27.000Z")
},
...,
...,
],
"lastTradeId" : 41306,
"dateStart" : ISODate("2017-04-21T21:37:39.000Z"),
"dateEnd" : ISODate("2017-04-21T21:37:39.000Z"),
"__v" : 0
}