将mongo聚合结果映射到数组

时间:2019-08-12 19:29:02

标签: json mongodb

我有一个如下所示的mongo查询:

db.myCollection.aggregate([ { 
    $group: { 
        _id: null,
        price: {
            $sum: "$price"
        },
        inventory: {
            $sum: "$inventory"
        }
    }
}])

返回哪个

{
    "_id" : null,
    "price" : 26,
    "inventory" : 5,
}

我想要一个查询,它希望返回如下内容:

[
    {
        name: "price",
        amount: 26
    },
    {
        name: "inventory",
        amount: 5
    }
]

编辑: 我如何用Spring Data用Java编写此代码?我可以分组求和,但不知道如何投影?

Aggregation aggregation = newAggregation(
                group("$id")
                        .sum("price").as("price")
                        .sum("inventory").as("inventory")
);

2 个答案:

答案 0 :(得分:1)

您需要使用$project。它使我们能够定义将要返回的字段及其格式。

db.myCollection.aggregate([{ 
    $group: { 
        _id: null,
        price: {
            $sum: "$price"
        },
        inventory: {
            $sum: "$inventory"
        }
    }
},
{
    $project: {
        _id: 0 //removes _id from result
        something: [
            {name: "price", amount: "$price"},
            {name: "inventory", amount: "$inventory"}
        ]    
    }
}])

这将为您提供:

{
    "something" : [ 
        {
            "name" : "price",
            "amount" : 26
        }, 
        {
            "name" : "inventory",
            "amount" : 5
        }
    ]
}

答案 1 :(得分:0)

您可以使用以下汇总

db.collection.aggregate([
  { "$project": {
    "data": {
      "$map": {
        "input": { "$objectToArray": "$$ROOT" },
        "in": { "name": "$$this.k", "amount": "$$this.v" }
      }
    }
  }},
  { "$unwind": "$data" },
  { "$replaceRoot": { "newRoot": "$data" }},
  { "$match": { "amount": { "$ne": null }}
  }
])
相关问题