MongoDB groupby-在字段中提取逗号分隔的值
我想按集合分组并提取逗号分隔的值 在下面的示例中,我想按“type”分组,并想在一个应该用逗号分隔的字段中提取“total”的$sum和“value”的所有可能唯一值 收藏:MongoDB groupby-在字段中提取逗号分隔的值,mongodb,mongodb-query,Mongodb,Mongodb Query,我想按集合分组并提取逗号分隔的值 在下面的示例中,我想按“type”分组,并想在一个应该用逗号分隔的字段中提取“total”的$sum和“value”的所有可能唯一值 收藏: [ { "type": "1", "value": "value1", "total": 10 }, { "type"
[
{
"type": "1",
"value": "value1",
"total": 10
},
{
"type": "1",
"value": "value3",
"total": 20
},
{
"type": "1",
"value": "value3",
"total": 30
},
{
"type": "2",
"value": "value1",
"total": 10
},
{
"type": "2",
"value": "value2",
"total": 20
}
]
我期望的输出:
[
{
"type": "1",
"value": "value1,value3",
"total": 60
},
{
"type": "2",
"value": "value1,value2",
"total": 30
}
]
请帮助提供方法或代码。仅使用$group和$project聚合方法即可实现此目的:
注意:使用
$addToSet
时,顺序未定义,您可以将数组转换为逗号分隔的字符串,如下所示:
db.collection.aggregate([
{
$group: {
_id: "$type",
value: {
$addToSet: "$value"
},
total: {
$sum: "$total"
}
},
},
{
$project: {
_id: 0,
type: "$_id",
value: "$value",
total: "$total"
}
},
])