'MongoDB query inside an array
I want to use this mongoDB collection:
[
{
"_id": {
"$oid": "627c4eb87e7c2b8ba510ac4c"
},
"Contact": [
{
"name": "ABC",
"phone": 5501234,
"mail": "[email protected]"
},
{
"name": "DEF",
"phone": 6001234,
"mail": "[email protected]"
}
],
"nomatter": "trash"
}
]
search for {"name":"ABC"}
and return only {"mail":"[email protected]"}
.
It's possible to use find or it's necessary to use aggregate?
Solution 1:[1]
Try this one:
db.collection.aggregate([
{ $match: { "Contact.name": "ABC" } },
{
$project: {
Contact: {
$filter: {
input: "$Contact",
cond: { $eq: [ "$$this.name", "ABC" ] }
}
}
}
},
{ "$replaceWith": { mail: { $first: "$Contact.mail" } } }
])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Wernfried Domscheit |