我有一份食谱文件,其中包含一系列成分(也包括文件)。我希望获得含有某种成分的所有食谱。
假设我有一份如下所示的食谱文件:
{
name: "Red Velvet Cake",
ingredients: [{
name: "roasted beet",
amount: {
quantity: 0.5,
metric: metrics[0]
}
}, {
name: "orange",
amount: {
quantity: 0.25,
metric: metrics[0]
}
}],
preparation: "Mix everything and have fun!",
Source: "Super Smoothies, p. 142"
}
现在,假设我有一个包含许多食谱的集合,我希望所有食谱都有"橙子"作为一种成分。
为了达到这个目的,我尝试使用mongodb的控制台:
db.smoothies.find( { ingredients: {name: "orange"}} )
但是,它不起作用。
我在其他问题中读到Find document with array that contains a specific value,有些人会使用$all
,$in
和$exists
这样的关键字,但我不确定这些可以帮助我。
如何让查询工作?
答案 0 :(得分:2)
像这样写下你的查询:
db.smoothies.find( { "ingredients.name": "orange"} )
答案 1 :(得分:-1)
不了解MongoDB,但这就是我用vanilla JavaScript做的方法:
var recipes = [{
name: "Red Velvet Cake - No Orange",
ingredients: [{
name: "roasted beet"
}]
}, {
name: "Red Velvet Cake",
ingredients: [{
name: "roasted beet"
}, {
name: "orange"
}]
}]
console.log(recipes
.find(function(a) {
return a.ingredients.some(function(b) {
return b.name == "orange"
});
}))
如果需要,可以填充:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find#Polyfill
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some#Polyfill