How to combine arrays from several documents in MongoDB?

Let's say I have a collection called "people" with the following documents:

{ "name": "doug", "colors": ["blue", "red"] } { "name": "jack", "colors": ["blue", "purple"] } { "name": "jenny", "colors": ["pink"] } 

How to get a concatenated array of all colors subarrays, i.e.?

 ["blue", "red", "blue", "purple", "pink"] 
+8
mongodb nosql
source share
2 answers

Try using the unit:

 db.people.aggregate([ {$unwind:"$colors"}, {$group:{_id:null, clrs: {$push : "$colors"} }}, {$project:{_id:0, colors: "$clrs"}} ]) 

Result:

 { "result" : [ { "colors" : [ "blue", "red", "blue", "purple", "pink" ] } ], "ok" : 1 } 

Update

If you want to get unique values ​​in an array of results, you can use $ addToSet instead of $push at the $group stage.

+15
source share

Ok, Try should work just fine for you!

 db.people.distinct("colors") 
+17
source share

All Articles