首页 > 解决方案 > 连接集合中元素的所有数组 [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 聚合,性能会改变吗?

标签: javascriptnode.jsmongodbmongooseaggregation-framework

解决方案


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

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

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


推荐阅读