MongoDb。展平内部数组

时间:2019-05-17 15:50:48

标签: mongodb mongodb-query aggregation-framework

我有一个包含以下结构的文档的集合:

{  
  "foo": [
    {
      "bar": [
        {
          "baz": [
            1,
            2,
            3
          ]
        },
        {
          "baz": [
            4,
            5,
            6
          ]
        }
      ]
    },
    {
      "bar": [
        {
          "baz": [
            7,
            8,
            9
          ]
        },
        {
          "baz": [
            10,
            11,
            12
          ]
        }
      ]
    }        
  ]
}

我想得到一个包含所有“条形”数组中所有值的平面数组。换句话说,我想要的结果看起来像[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] 我该怎么办?

1 个答案:

答案 0 :(得分:3)

您可以使用$reduce运算符

使用以下聚合
db.collection.aggregate([
  { "$project": {
    "array": {
      "$reduce": {
        "input": {
          "$reduce": {
            "input": "$foo",
            "initialValue": [],
            "in": { "$concatArrays": ["$$this.bar", "$$value"] }       
          }
        },
        "initialValue": [],
        "in": { "$concatArrays": ["$$this.baz", "$$value"] }
      }
    }
  }}
])

MongoPlayground

使用$unwind运算符

db.collection.aggregate([
  { "$unwind": "$foo" },
  { "$unwind": "$foo.bar" },
  { "$unwind": "$foo.bar.baz" },
  { "$group": {
    "_id": "$_id",
    "array": {
      "$push": "$foo.bar.baz"
    }
  }}
])

MongoPlayground