伙计们!我的 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/