【问题标题】:Concat all the arrays from different objects in mongoDB连接来自 mongoDB 中不同对象的所有数组
【发布时间】:2018-10-18 13:27:02
【问题描述】:

我开始发现 mongodb ,我想将 images 连接到同一个数组中

例子:

{user_id:01, images:[10,20,30,40,50]}
{user_id:02, images:[11,22,33,44,55]}
{user_id:03, images:[12,22,32,42,52]}
{user_id:04, images:[13,23,33,43,53]}

想要的结果:

 images:[10,20,30,40,50,11,22,33,44,55,12,22,32,42,52,13,23,33,43,53]

我通过文档找到了$aggreagation 解决方案,这是我尝试过的:

  db.results.aggregate([{ $project: { images: { $concatArrays: ["$images"]}}}])

但它只是从同一对象连接数组,在我的情况下,正如我在 result wanted 中提到的那样,将来自不同对象的所有名称为 images 的数组连接为一个

【问题讨论】:

    标签: arrays mongodb mongodb-query concatenation aggregation-framework


    【解决方案1】:

    你需要两个步骤:

    $group 使用 const 值(如 null)作为分组 _id 以获取数组数组(来自所有文档),$reduce 以展平所有数组

    db.collection.aggregate([
        {
            $group: {
                _id: null,
                images: { $push: "$images"}
            }
        },
        {
            $project: {
                _id: 0,
                images: {
                    $reduce: {
                        input: "$images",
                        initialValue: [],
                        in: {
                            $concatArrays: [ "$$this", "$$value"]
                        }
                    }
                }
            }
        }
    ])
    

    【讨论】:

    • 感谢您的帮助,我尝试执行此查询,但它给了我这个错误:2018-05-08T14:56:35.743+0000 E QUERY [thread1] SyntaxError: missing : after property id @(shell):5:16 via mongo CLI,顺便说一下我的mongoDB version is 3.4
    • 它正在工作,我用空格命名该字段,这就是为什么它不起作用谢谢:-)
    • ,有没有办法不显示标签字段images,因为我应该在文件中将所有images的数字分组
    • @Data_Geek 聚合的输出必须是有效的 JSON (BSON),因此您可以在包含数组的文档或多个文档中拥有单个项目,我猜这不是您想要实现的目标
    • 我明白你的意思,无论如何感谢您的时间和帮助
    【解决方案2】:

    您可以运行以下聚合查询来获取结果:

    db.collection.aggregate([
    {
        $unwind: "$images" // flatten the "images" array into separate documents
    },
    {
        $group: { // group all documents
            "_id": null, // into the same bucket
            "images": { $push: "$images"} // and push every image entry into an array called "images"
        }
    },
    {
        $project: {
            _id: 0 // to get rid of the "_id" field if needed
        }
    }])
    

    【讨论】:

    • 这是解决方案的第 2 版,但如何不显示 _id 字段??
    • 有人可以向我解释为什么这个答案被否决了吗?
    • 我不知道怎么回事,我注意到了这个问题,答案以某种方式被否决了
    猜你喜欢
    • 1970-01-01
    • 2021-08-02
    • 2018-08-17
    • 1970-01-01
    • 2013-01-22
    • 2022-11-30
    • 2018-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多