假设以下结构:
'kitchenThings': [
{'foods': [
{'name': 'cakes',
'ingredients': [
{name: 'Sugar', healthy: false},
{name: 'Butter', healthy: false},
{name: 'Flour', healthy: true}
]
}
}
]
我将运行什么查询来仅检索包含healthy: false
的kitchenThings?我的第一个猜测是
{ { 'foods.ingredients.healthy': false } }
但返回0条记录。我不知道从哪里去。有人可以帮忙吗?我的预期产量完全如上,但不匹配的成分(面粉)不存在。只需返回匹配的成分(可能是通过投影?)也可以。
由于
答案 0 :(得分:2)
要获取包含至少一种 healthy : false
成分的食物清单,您可以使用aggregation pipeline。
一种可能的解决方案可能如下:
db.test.aggregate([
{"$unwind": "$foods"},
{"$match": {
"foods.ingredients.healthy": false
}},
{"$project":{
"_id": 0,
"food": "$foods"
}}
])
测试用例:
db.test.insert({
'foods': [
{'name': 'cakes',
'ingredients': [
{name: 'Sugar', healthy: false},
{name: 'Butter', healthy: false},
{name: 'Flour', healthy: true}
]
},
{'name': 'fuits',
'ingredients': [
{name: 'Fiber', healthy: true},
{name: 'Vitamins', healthy: true}
]
},
{'name': 'cookies',
'ingredients': [
{name: 'Sugar', healthy: false},
{name: 'Butter', healthy: false},
{name: 'Flour', healthy: true}
]
},
]
})
结果:
{ "food" : { "name" : "cakes", "ingredients" : [ { "name" : "Sugar", "healthy" : false }, { "name" : "Butter", "healthy" : false }, { "name" : "Flour", "healthy" : true } ] } }
{ "food" : { "name" : "cookies", "ingredients" : [ { "name" : "Sugar", "healthy" : false }, { "name" : "Butter", "healthy" : false }, { "name" : "Flour", "healthy" : true } ] } }