繁体   English   中英

连接集合中所有元素的数组[MongoDB]

[英]Concatenate all the arrays of the elements in a collection [MongoDB]

对不起,我没有很好地获得MongoDB聚合。 如何通过聚合实现:

[
  {array: [1,2,3] },
  {array: [4,5,6] },
  {array: [7,8,9] }
]


desired result:
[1,2,3,4,5,6,7,8,9]

如果不使用MongoDB聚合,我会将文档视为普通对象吗?

聚合总是一个更好的选择,而不是使用一些语言代码,这就是为什么数据库提供这种类型的缓解来一次性获得结果。

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

这里唯一需要注意的是单个文档返回结果的大小不应超过16MB Bson限制。 您可以从这里学到更多

您可以$组null得到数组作为一个单一的文件的数组,然后你可以运行$减少$ concatArrays扁平化数组:

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

MongoDB游乐场

暂无
暂无

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

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