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"]
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.
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.
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.
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.
Well, Try should work fine for you!!
db.people.distinct("colors")
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With