1
votes

Is there any possible way to combine two documents in mongodb?

Imagine I have a collection with this documents:

{ "_id":ObjectId("142342432"), "name":"Chris", "surname":"Patrick", "pets":["dog", "cat"] }
{ "_id":ObjectId("142342752"), "name":"Chris", "surname":"Patrick", "pets":["lizard"] }
more than x2000 documents

And some other documentes. My idea would be to group each of the entries by name and surname and in case they match, join the pets array $addToSet.

The idea is to delete those two documents and add a new one with a new generated id and the combination. Deleting one document and appending the array to the other one, would also be ok.

My main problem is that I should be updating the collection, so it wouldn't be just a dump. And it can't be inefficient to dump it into a file and import it later on.

Thanks!

Update: Using mongodb 3.4

1
What mongod version are you using? - styvane
@StyvaneS. I'm using mongod 3.4 - lpares12

1 Answers

3
votes

you can achieve this in a single query :

  • first, unwind pets array
  • then, group by name and surname, and combine arrays with $addToSet
  • finally, write the output to the same collection using $out

Be carefull, this will overwrite the original collection! before running this, you should create a dump of your current collection to avoid any data loss

here is the query:

db.collectionName.aggregate([  
   { $unwind: {
       path: "$pets",
       preserveNullAndEmptyArrays: true
       }
   },
   {  
      $group:{  
         _id:{  
            name:"$name",
            surname:"$surname"
         },
         pets:{  
            $addToSet:"$pets"
         }, 
         otherField: {
            $first: "$otherField"
         }
      }
   },
   {  
      $out:"collectionName"
   }
])