【发布时间】:2017-03-20 14:41:28
【问题描述】:
目标
我有一个包含一系列成分的食谱文档(也是文档)。我希望获得所有包含某种成分的食谱。
背景
假设我有一个如下所示的食谱文档:
{
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 等关键字,但我不确定这些对我有何帮助。
问题
如何使我的查询工作?
【问题讨论】:
-
使用dot notation查询数组元素
db.smoothies.find({ "ingredients.name": "orange" })或$elemMatch为db.smoothies.find({ "ingredients": { "$elemMatch": { "name": "orange" } } })
标签: javascript arrays node.js mongodb mongoose