繁体   English   中英

MongoDB groupby - 拉取字段中的逗号分隔值

[英]MongoDB groupby - pull comma separated values in a field

我想对集合进行分组,并想提取逗号分隔的值。

在下面的示例中,我想按“类型”进行分组,并希望在应以逗号分隔的字段中提取“总计”的 $sum 和所有可能的“值”唯一值。

收藏:

[
    {
        "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
    }
]

我期待的 output:

[
    {
        "type": "1",
        "value": "value1,value3",
        "total": 60
    },
    {
        "type": "2",
        "value": "value1,value2",
        "total": 30
    }
]

请帮忙提供方法或代码。

这可以通过 $group 和 $project 聚合方法来实现:

https://mongoplayground.net/p/230nt_AMFIm

db.collection.aggregate([
  {
    $group: {
      _id: "$type",
      value: {
        $addToSet: "$value"
      },
      total: {
        $sum: "$total"
      }
    },
    
  },
  {
    $project: {
      _id: 0,
      type: "$_id",
      value: "$value",
      total: "$total"
    }
  },
])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM