You need to perform an aggregation operation with two unwind stages and one group . The basic rule is that you unwind as many times as the level of nest depth. Here the nesting level is 2, so we unwind twice.
collection.aggregate([ {$unwind => "$Countries"}, {$unwind => "$Countries"}, {$group => {"_id":"$_id","Countries":{$push => "$Countries"}}} ])
The first step of $unwind yields the result:
{ "_id" : ObjectId("54a32e0fc2eaf05fc77a5ea4"), "Countries" : [ "Spain", "France" ] } { "_id" : ObjectId("54a32e4ec2eaf05fc77a5ea5"), "Countries" : [ "Spain" ] } { "_id" : ObjectId("54a32e4ec2eaf05fc77a5ea5"), "Countries" : [ "Russia", "Egypt" ] }
The second step of $unwind further aligns the Countries array:
{ "_id" : ObjectId("54a32e0fc2eaf05fc77a5ea4"), "Countries" : "Spain" } { "_id" : ObjectId("54a32e0fc2eaf05fc77a5ea4"), "Countries" : "France" } { "_id" : ObjectId("54a32e4ec2eaf05fc77a5ea5"), "Countries" : "Spain" } { "_id" : ObjectId("54a32e4ec2eaf05fc77a5ea5"), "Countries" : "Russia" } { "_id" : ObjectId("54a32e4ec2eaf05fc77a5ea5"), "Countries" : "Egypt" }
Now the last step of $group groups records based on _id and accumulates country names in one array.
{ "_id" : ObjectId("54a32e4ec2eaf05fc77a5ea5"), "Countries" : [ "Spain", "Russia", "Egypt" ] } { "_id" : ObjectId("54a32e0fc2eaf05fc77a5ea4"), "Countries" : [ "Spain", "France" ] }
If you want to save other fields in the document, you need to explicitly specify the names of fields other than the country field (field1, field2, etc.) using the $first operator. You can write / overwrite a collection by specifying the name of the collection at the $out stage.
collection.aggregate([ {$unwind => "$Countries"}, {$unwind => "$Countries"}, {$group => {"_id":"$_id","Countries":{$push => "$Countries"}, "field1":{$first => "$field1"}}}, {$out => "collection"} ])
You need to explicitly specify the fields so that you do not get a redundant Countries field.
The $$ROOT variable can be used to store the entire document, but this will make the Countries field redundant. One outside the doc and one inside the doc .
collection.aggregate([ {$unwind => "$Countries"}, {$unwind => "$Countries"}, {$group => {"_id":"$_id","Countries":{$push => "$Countries"}, "doc":{$first => "$$ROOT"}}}, {$out => "collection"} ])