我想使用這個 mongoDB 集合:
[
{
"_id": {
"$oid": "627c4eb87e7c2b8ba510ac4c"
},
"Contact": [
{
"name": "ABC",
"phone": 5501234,
"mail": "[email protected]"
},
{
"name": "DEF",
"phone": 6001234,
"mail": "[email protected]"
}
],
"nomatter": "trash"
}
]
僅搜索{"name":"ABC"}并回傳{"mail":"[email protected]"}。
可以使用查找還是有必要使用聚合?
uj5u.com熱心網友回復:
試試這個:
db.collection.aggregate([
{ $match: { "Contact.name": "ABC" } },
{
$project: {
Contact: {
$filter: {
input: "$Contact",
cond: { $eq: [ "$$this.name", "ABC" ] }
}
}
}
},
{ "$replaceWith": { mail: { $first: "$Contact.mail" } } }
])
蒙戈游樂場
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/474007.html
上一篇:MongoDB-遍歷陣列陣列
