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

标签 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
    }
  ]
}

你觉得我应该怎么做?

提前致谢!!!

最佳答案

您可以使用以下聚合。

$group 按月和年和 $push 使用 $$ROOT 访问整个文档,然后是 $sort 月和年描述。

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

关于mongodb - 按月和年对 MongoDB 中的数据进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49324000/

相关文章:

ruby - 对混合了整数和字符串的数组进行排序 - Ruby

mongodb - 那个领域不一样的Mongo投影领域

json - MongoDB 文档 : empty value or omit pair altogether?

java - 如何在java中使用mongodb嵌入模式

arrays - 确定一个非常大的数组是否包含重复项

c# - 对包含坐标 x 和 y 的 List<String> 进行排序

node.js - 如何使用聚合将两个数组的相应元素相乘?

mongodb - 数组字段包含其他字段的数组值

node.js - 如何在 Mongoose 中立即在$map之后使用$filter

node.js - 错误 ReferenceError : ObjectID is not defined