Merge two array field in mongoDB

后端 未结 2 792
梦毁少年i
梦毁少年i 2020-12-12 01:16

I have a collection of the following structure

{
   _id : ObjectId(\"52f0795a58c5061aa34d436a\"),
   \"attribute1\" : [1, 3, 6, 7],
   \"attribute2\" : [2, 4         


        
2条回答
  •  醉酒成梦
    2020-12-12 02:08

    Using the .aggregate() method and the $setUnion operator.

    db.collection.aggregate([
        { "$project": { 
            "attribute3": { "$setUnion": [ "$attribute1", "$attribute2" ] } 
        }}
    ])
    

    Which yields:

    {
        "_id" : ObjectId("52f0795a58c5061aa34d436a"),
        "attribute3" : [8, 4, 2, 6, 3, 7, 1]
    }
    

提交回复
热议问题