这是mongo聚合文档中的正确内容。假设我有这些文件:
{ _id: 1, cust_id: "abc1", ord_date: ISODate("2012-11-02T17:04:11.102Z"), status: "A", amount: 50 }
{ _id: 2, cust_id: "xyz1", ord_date: ISODate("2013-10-01T17:04:11.102Z"), status: "A", amount: 100 }
{ _id: 3, cust_id: "xyz1", ord_date: ISODate("2013-10-12T17:04:11.102Z"), status: "D", amount: 25 }
{ _id: 4, cust_id: "xyz1", ord_date: ISODate("2013-10-11T17:04:11.102Z"), status: "D", amount: 125 }
{ _id: 5, cust_id: "abc1", ord_date: ISODate("2013-11-12T17:04:11.102Z"), status: "A", amount: 25 }
我可以运行这个聚合查询:
db.orders.aggregate([
{ $match: { status: "A" } },
{ $group: { _id: "$cust_id", total: { $sum: "$amount" } } },
{ $sort: { total: -1 } }
])
获得此回复:
{ "_id" : "xyz1", "total" : 100 }
{ "_id" : "abc1", "total" : 75 }
但是如果想要以嵌套格式进行响应呢?没有使用mapReduce的任何方法实现这一点?像这样:
{ "_id" : "xyz1", "amount": { "total" : 100 } }
{ "_id" : "abc1", "amount": { "total" : 75 } }
答案 0 :(得分:1)
您需要使用$project
运算符
db.collection.aggregate([
{ "$group": {
"_id": "$cust_id",
"total": { "$sum": "$amount" }
}},
{ "$project": { "amount.total": "$total" } },
{ "$sort": { "amount.total": -1 } }
])
返回:
{ "_id" : "xyz1", "amount" : { "total" : 250 } }
{ "_id" : "abc1", "amount" : { "total" : 75 } }