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?
CodePudding user response:
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" } } }
])