Reputation: 20223
I have this MongoDB collection:
{ "_id" : ObjectId("123"), "from_name" : "name", "from_email" : "[email protected]", "to" : [ { "name" : "domains", "email" : "[email protected]" } ], "cc" : [ ], "subject" : "mysubject" }
My goal is to search in this collection by the "to" with some email.
Upvotes: 0
Views: 737
Reputation: 151092
If you only want one field then MongoDB has "dot notation" for accessing nested elements:
db.collection.find({ "to.email": "[email protected]" })
And this will return documents that match:
For more that one field as a condition, use the $elemMatch
operator
db.collection.find(
{ "to": {
"$elemMatch": {
"email": "[email protected]",
"name": "domains",
}
}}
)
And you can "project" a single match to just return that element:
db.collection.find({ "to.email": "[email protected]" },{ "to.$": 1 })
But if you expect more than one element to match, then you use the aggregation framework:
db.collection.aggregate([
// Matches the "documents" that contain this
{ "$match": { "to.email": "[email protected]" } },
// De-normalizes the array
{ "$unwind": "$to" },
// Matches only those elements that match
{ "$match": { "to.email": "[email protected]" } },
// Maybe even group back to a singular document
{ "$group": {
"_id": "$_id",
"from_name": { "$first": "$name" },
"to": { "$push": "$to" },
"subject": { "$first": "$subject" }
}}
])
All fun ways to match on and/or "filter" the content of an array for matches if required.
Upvotes: 2