guys! I have this data inside my MongoDB:
{
"_id" : ObjectId("5aa35c78e84868839683c4ca"),
"dateTransacted" : ISODate("2018-03-10T04:18:00.074Z"),
"taskerFee" : 1500,
"customerFee" : 4000,
"transactionFee" : 50,
"mnmltaskrProfit" : 30
},
{
"_id" : ObjectId("5aa3ac08e84868839683c4cb"),
"dateTransacted" : ISODate("2018-03-10T09:57:28.637Z"),
"taskerFee" : 300,
"customerFee" : 1500,
"transactionFee" : 50,
"mnmltaskrProfit" : 60
}
and I want to query this by month and year so that it would return something like:
{
'month': 'September',
'year': 2018,
'transactions': [
{
"_id" : ObjectId("5aa3ac08e84868839683c4cb"),
"dateTransacted" : ISODate("2018-03-10T09:57:28.637Z"),
"taskerFee" : 300,
"customerFee" : 1500,
"transactionFee" : 50,
"mnmltaskrProfit" : 60
},
{
"_id" : ObjectId("5aa3ac08e84868839683c4cb"),
"dateTransacted" : ISODate("2018-03-10T09:57:28.637Z"),
"taskerFee" : 300,
"customerFee" : 1500,
"transactionFee" : 50,
"mnmltaskrProfit" : 60
}
]
}
what do you suppose i should do?
THANKS IN ADVANCE!!!
You can use below aggregation.
$group
by month and year and $push
with $$ROOT
to access the whole document followed by $sort
on month and year desc.
db.collection.aggregate([
{"$group":{
"_id":{"month":{"$month":"$dateTransacted"},"year":{"$year":"$dateTransacted"}},
"transactions":{"$push":"$$ROOT"}
}},
{"$sort":{"month":-1,"year":-1}}
])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With