Reputation: 1447
This is an example of a document I have:
{ _id: "Y5nf7Hh6DskxjjMEZ",
createdAt: ISODate("2015-01-05T01:58:09.365Z"),
email_hash: "1basdfkjasldfsomethinghashedalsdjf23",
emails: [
{ address: "[email protected]",
verified: false }
],
isAdmin: false,
karma: 0,
postCount: 0,
profile: { email: "[email protected]",
notifications: { users: false,
posts: false
},
subscribed: true,
username: "hermione"
},
services: { password: { bcrypt: "$23098somethingencrypted23094" },
resume: { loginTokens: [] } },
slug: "Hermione",
status: { online: false },
username: "hermione"
}
I'm trying to return all the e-mail addresses something equivalent to the idea of SELECT emails.address FROM users
or SELECT profile.email FROM users;
How do I do this with Mongo?
Upvotes: 2
Views: 683
Reputation: 2091
Because field emails is an array, I suggest you to use $unwind(aggregation)
to get emails out of the array first,then combine the result with $project(aggregation)
, to get SELECT emails.address FROM users
db.collection.aggregate( [ { $unwind : "$emails" },{$project:{ field1:1,field2:1,... ] )
Upvotes: 1
Reputation: 222761
It looks like people think that this is a proper question, so here is your solution:
var mails = [];
db.a.find({},{'emails.address' : 1}).forEach(function(o){
for (var i = 0; i < o.emails.length; i++){
mails.push(o.emails[i].address)
}
})
put this in mongoshell and mails will have all your email addresses. Note that each document should have at least one address. If this is not the case, add one line which verifies it.
Upvotes: 1