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

时间:2018-03-16 15:10:17

标签: mongodb sorting 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
}

我希望按月和年查询,以便返回类似的内容:

{
  '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
    }
  ]
}
你认为我该怎么办?

感谢提前!!!

1 个答案:

答案 0 :(得分:1)

您可以使用以下聚合。

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

db.collection.aggregate([
  {"$group":{
    "_id":{"month":{"$month":"$dateTransacted"},"year":{"$year":"$dateTransacted"}},
    "transactions":{"$push":"$$ROOT"}
  }},
  {"$sort":{"month":-1,"year":-1}}
])
相关问题