Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate arrays from multiple documents in MongoDB?

Tags:

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 would I get a concatenated array of all the colors subarrays, i.e.?

["blue", "red", "blue", "purple", "pink"] 
like image 398
lmirosevic Avatar asked Sep 02 '13 16:09

lmirosevic


People also ask

How to concat two arrays in MongoDB?

Concatenates arrays to return the concatenated array. $concatArrays has the following syntax: { $concatArrays: [ <array1>, <array2>, ... ] } The <array> expressions can be any valid expression as long as they resolve to an array.

How do I append to a list in MongoDB?

In MongoDB, the $push operator is used to appends a specified value to an array. If the mentioned field is absent in the document to update, the $push operator add it as a new field and includes mentioned value as its element.

How append an element in array from MongoDB?

If the value is an array, $push appends the whole array as a single element. To add each element of the value separately, use the $each modifier with $push . For an example, see Append a Value to Arrays in Multiple Documents. For a list of modifiers available for $push , see Modifiers.

Can MongoDB store arrays?

One of the benefits of MongoDB's rich schema model is the ability to store arrays as document field values. Storing arrays as field values allows you to model one-to-many or many-to-many relationships in a single document, instead of across separate collections as you might in a relational database.


2 Answers

Well, Try should work fine for you!!

db.people.distinct("colors") 
like image 52
Anuj Aneja Avatar answered Sep 22 '22 07:09

Anuj Aneja


Try to use aggregate:

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 } 

Updated

If you want to get unique values in result's array, you could use $addToSet operator instead of $push in the $group stage.

like image 32
Yevgeniy Anfilofyev Avatar answered Sep 24 '22 07:09

Yevgeniy Anfilofyev