【问题标题】:Extract unique values from Array in aggregation pipeline从聚合管道中的数组中提取唯一值
【发布时间】:2022-01-18 22:50:57
【问题描述】:

在我的聚合管道中,经过一些先前的聚合后,我最终得到了类似于这些的文档:

[
  {
    "_id": 0,
    "group": "Electronics",
    // other fields omitted for brevity
    "articles": [
      {
        "name": "Gameboy",
        // Even more fields omitted for brevity
        "area": "Video Games"
      },
      {
        "name": "Playstation",
        "area": "Video Games"
      },
      {
        "name": "Refrigerator",
        "area": "White Goods"
      }
    ]
  },
  {
    "_id": 1,
    "group": "Food",
    "articles": [
      {
        "name": "Apple",
        "area": "Fruit"
      },
      {
        "name": "Pear",
        "area": "Fruit"
      }
    ]
  }
]

我需要从数组中提取唯一的 area 值,同时保持文档的其余部分完好无损(尽管之后不需要 articles)。结果应如下所示:


[
    {
        "_id": 0,
        "group": "Electronics",
        // other fields...
        "articleAreas": [ "Video Games", "White Goods" ]
    },
    {
        "_id": 1,
        "group": "Food",
        "articleAreas": [ "Fruit" ]
    }
]

我的直觉是应该有一些的方式来使用$addToSet,类似于在$group 阶段可以做的事情,但我不知道怎么做。

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案1】:

    您可以尝试$addFields 阶段和$setUnion 运算符从数组中获取唯一值,

    • $addFields 添加新字段 articleAreas
    • $setUnionarticles.area 获取值数组中的唯一值
    db.collection.aggregate([
      {
        $addFields: {
          articleAreas: {
            $setUnion: "$articles.area"
          }
        }
      }
    ])
    

    Playground

    【讨论】:

      猜你喜欢
      • 2018-05-21
      • 2021-04-15
      • 2013-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 2020-12-12
      • 1970-01-01
      相关资源
      最近更新 更多