MongoDB aggregate, how to addToSet each element of array in group pipeline

≡放荡痞女 提交于 2019-11-29 16:41:28

To mimic functionality of $addToSet update operator with $each modifier in aggregation pipeline you can use a combination of $push on grouping stage and $reduce + $setUnion on projection stage. E.g.:

db.collection.aggregate([
    {$group:{
       _id: null,
       selectedTags: { $push: '$tags' }      
    }},
    {$project: {
        selectedTags: { $reduce: {
            input: "$selectedTags",
            initialValue: [],
            in: {$setUnion : ["$$value", "$$this"]}
        }}
    }}
])

results with a single document which contains a distinct list of tags from all documents in selectedTags array.

You can also use $unwind to get result:

db.collection.aggregate([
  {$unwind: "$tags"},
  {$group:{
     _id: null,
     selectedTags: { $addToSet: '$tags' }      
  }}
])
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!