$reduce and $setUnion for nested arrays in MongoDB

后端 未结 1 1962
天命终不由人
天命终不由人 2020-12-12 02:56

I am looking to merge nested arrays using $reduce and $setUnion in MongoDB. Following is the sample input -

levels: [
 [[80,100,120]],[[100,150]],[[200,80,10         


        
相关标签:
1条回答
  • 2020-12-12 03:43

    You can use below aggregation with single $project stage

    db.collection.aggregate([
      { "$project": {
        "levels": {
          "$reduce": {
            "input": {
              "$reduce": {
                "input": "$levels",
                "initialValue": [],
                "in": { "$setUnion": ["$$this", "$$value"] }
              }
            },
            "initialValue": [],
            "in": { "$setUnion": ["$$this", "$$value"] }
          }
        }
      }}
    ])
    
    0 讨论(0)
提交回复
热议问题