Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort data from MongoDB by month and year

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!!!

like image 554
nrion Avatar asked Sep 20 '25 13:09

nrion


1 Answers

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}}
])
like image 195
s7vr Avatar answered Sep 22 '25 23:09

s7vr