【问题标题】:Nested output from mongo aggregate querymongo 聚合查询的嵌套输出
【发布时间】:2016-01-27 23:39:40
【问题描述】:

这是 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 } }

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案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 } }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多