Diskdrive Diskdrive - 6 months ago 43
JSON Question

Return the values of one variable of subdocument in my collection

I'm trying to write a mongodb query.

I have a whole set of documents in this format

{
"_id" : "_id1",
"participants" : [
{
"email" : "email0@gmail.com"
},
{
"email" : "email1@gmail.com"
},
{
"email" : "email2@outlook.com"
}
]
}


{
"_id" : "_id2",
"participants" : [
{
"email" : "email3@gmail.com"
},
{
"email" : "email4@gmail.com"
}
]
}


I would like to get an array returned from mongodb which would only have the emails like this

[email0@gmail.com, email1@gmail.com,email2@gmail.com,email3@gmail.com,email4@gmail.com]


Is this possible to do in Mongodb 2.6?

Answer
db.collection.aggregate([
    { $unwind: "$participants" },
    { $group : { _id : null, emails: { $push: "$participants.email" } } },       
    { $project: {"_id":0, emails:1}}
 ])

Result of this will be

{
    "emails" : [ 
        "email0@gmail.com", 
        "email1@gmail.com", 
        "email2@outlook.com", 
        "email3@gmail.com", 
        "email4@gmail.com"
    ]
}

If you want only unqiue emails, then you can use $addToSet instead of $push in the $group stag