【问题标题】:Concatenate all the arrays of the elements in a collection [MongoDB]连接集合中元素的所有数组 [MongoDB]
【发布时间】:2019-10-20 08:28:32
【问题描述】:

抱歉,我没有很好地了解 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 聚合,性能会改变吗?

【问题讨论】:

    标签: javascript node.js mongodb mongoose aggregation-framework


    【解决方案1】:

    您可以通过$group null 将数组数组作为单个文档获取,然后您可以运行 $reduce$concatArrays 以展平该数组:

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

    MongoDB Playground

    【讨论】:

      【解决方案2】:

      聚合总是比使用某些语言代码更好的选择,这就是为什么数据库提供这种类型的救济以一次性获得结果。

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

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

      【讨论】:

      • 非常感谢您和@mickl。在我的项目中,为了避免 16MB 的限制,我将数组分成了几个文档。出于这个原因,我相信数组会超出限制。所以对于我的情况,最好使用一些语言代码?
      • 是的,但我认为 16 mb 不是一个小单位。
      猜你喜欢
      • 1970-01-01
      • 2022-09-28
      • 1970-01-01
      • 1970-01-01
      • 2020-10-19
      • 2019-04-08
      • 2021-08-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多