25

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"]

2 Answers 2

34

Well, Try should work fine for you!!

db.people.distinct("colors")
Sign up to request clarification or add additional context in comments.

3 Comments

simple and efficient! this answer should be the accepted one.
very good, exactly what I needed; it is also good to know that you can pass an optional query to distinct to filter out the results. source
This doesn't answer the question. This returns only the distinct colors, while the accepted answer returns all the arrays concatenated.
30

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.

2 Comments

HI but if i need unique value in result how i will achieve that as this will give duplicate entry in this array
For sure. To do this you could change $push operator with $addToSet in {$group:{_id:null, clrs: {$push : "$colors"} }}, string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.