如何在MongoDB聚合框架中收集数组对象的值以将数组分开?

huangapple go评论63阅读模式
英文:

How to collect array objects' values to separate the array in MongoDB Aggregation Framework?

问题

这是收藏内容的示例:

博客作者

[
    {
        _id: ObjectId(...),
        posts: [
            {
                "platform": "instagram"
            },
            {
                "platform": "tiktok"
            },
        ],
        full_name: "John Doe",
    },
    {
        _id: ObjectId(...),
        posts: [
            {
                "platform": "youtube"
            },
            {
                "platform": "tiktok"
            },
        ],
        full_name: "Mamed Mamedov"
    }
]

聚合的结果,我想要得到类似于这样的东西:

[
    {
        _id: ObjectId(...),
        platforms: ["instagram", "tiktok"],
        full_name: "John Doe",
    },
    {
        _id: ObjectId(...),
        platforms: ["youtube", "tiktok"],
        full_name: "Mamed Mamedov"
    }
]

(从 posts 字段的平台列表)

英文:

Here is the example of collection content:

bloggers

[
    {
        _id: ObjectId(...),
        posts: [
            {
                "platform": "instagram"
            },
            {
                "platform": "tiktok"
            },
        ],
        full_name: "John Doe",
    },
    {
        _id: ObjectId(...),
        posts: [
            {
                "platform": "youtube"
            },
            {
                "platform": "tiktok"
            },
        ],
        full_name: "Mamed Mamedov"
    }
]

And as a result of the aggregation, I wanna get something like this:

[
    {
        _id: ObjectId(...),
        platforms: ["instagram", "tiktok"],
        full_name: "John Doe",
    },
    {
        _id: ObjectId(...),
        platforms: ["youtube", "tiktok],
        full_name: "Mamed Mamedov"
    }
]

(List of the platforms from posts field)

For now, I even not sure, that there is some ready-to-use method in mongodb.

答案1

得分: 0

你可以使用$reduce 轻松完成这个操作:

db.collection.aggregate([
  {
    "$project": {
      "full_name": 1,
      "platforms": {
        "$reduce": {
          "input": "$posts",
          "initialValue": [],
          "in": {
            "$concatArrays": [
              "$$value",
              [
                "$$this.platform"
              ]
            ]
          }
        }
      }
    }
  }
])

示例

英文:

You can do this easy with $reduce:

db.collection.aggregate([
{
"$project": {
  "full_name":1,
  "platforms": {
    "$reduce": {
      "input": "$posts",
      "initialValue": [],
      in: {
        $concatArrays: [
          "$$value",
          [
            "$$this.platform"
          ]
        ]
      }
    }
   }
  }
 }
])

example

huangapple
  • 本文由 发表于 2023年3月3日 18:40:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75626012.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定