按月份和年份对 MongoDB 中的数据进行排序

nri*_*ion 4 sorting mongodb aggregation-framework

伙计们!我的 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
}
Run Code Online (Sandbox Code Playgroud)

我想按月和年查询它,以便它返回类似以下内容的内容:

{
  '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
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

你认为我应该做什么?

提前致谢!!!

use*_*814 5

您可以使用下面的聚合。

$group按月份和年份,然后$push访问$$ROOT整个文档,然后按$sort月份和年份 desc。

db.collection.aggregate([
  {"$group":{
    "_id":{"month":{"$month":"$dateTransacted"},"year":{"$year":"$dateTransacted"}},
    "transactions":{"$push":"$$ROOT"}
  }},
  {"$sort":{"month":-1,"year":-1}}
])
Run Code Online (Sandbox Code Playgroud)