如何在 MongoDB 中连接来自多个文档的数组? [英] How to concatenate arrays from multiple documents in MongoDB?

查看:17
本文介绍了如何在 MongoDB 中连接来自多个文档的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个名为people"的集合,其中包含以下文档:

Let's say I have a collection called 'people' with the following documents:

{
    "name": "doug",
    "colors": ["blue", "red"]
}

{
    "name": "jack",
    "colors": ["blue", "purple"]
}

{
    "name": "jenny",
    "colors": ["pink"]
}

如何获得所有 colors 子数组的串联数组,即?

How would I get a concatenated array of all the colors subarrays, i.e.?

["blue", "red", "blue", "purple", "pink"]

推荐答案

尝试使用聚合:

db.people.aggregate([
  {$unwind:"$colors"},
  {$group:{_id:null, clrs: {$push : "$colors"} }},
  {$project:{_id:0, colors: "$clrs"}}
])

结果:

{
"result" : [
    {
        "colors" : [
            "blue",
            "red",
            "blue",
            "purple",
            "pink"
        ]
    }
],
"ok" : 1
}

更新

如果您想在结果数组中获取唯一值,可以使用 $addToSet 操作符代替 $group 阶段中的 $push.

If you want to get unique values in result's array, you could use $addToSet operator instead of $push in the $group stage.

这篇关于如何在 MongoDB 中连接来自多个文档的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆