Merge two array field in mongoDB

后端 未结 2 747
梦毁少年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

    If you want to modify your data you can use $addToSet with the $each modifier once you have read the contents of one of the arrays. These would be individual updates as you cannot refer to another element of the document in an update operation.

    If you really just want this for aggregation and can wait, then the upcoming release of MongoDB adds new set operators to aggregation. Particularly there is $setUnion which will do exactly what you want.

    0 讨论(0)
  • 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]
    }
    
    0 讨论(0)
提交回复
热议问题