[英]MongoDB query for nested array of specific object
使用$
進行投影。
查詢 1
db.collection.find({
"people.age": {
$in: [
24
]
}
},
{
"people.$": 1
})
如果您只是按特定年齡搜索人,您也可以使用以下查詢:
查詢 2
db.collection.find({
"people.age": 24
},
{
"people.$": 1
})
注意: $
將只返回數組的第一個元素。
您可以將聚合查詢查找為:
$match
- 按age
過濾文檔。$project
- 裝飾 output 個文檔。 使用$filter
運算符過濾people
數組中的文檔。db.collection.aggregate([
{
$match: {
"people.age": 24
}
},
{
$project: {
"people": {
$filter: {
input: "$people",
cond: {
$eq: [
"$$this.age",
24
]
}
}
}
}
}
])
參考
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.