如何获取包含数组中另一个文档的所有文档?

目的

我有一个配方文件,其中包含一系列成分(也是文件)。 我希望获得所有包含某种成分的食谱。

背景

比方说,我有一个配方文件,如下所示:

{ 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"}} ) 

但是,它不起作用。

我阅读其他问题,如查找文档与数组,其中包含一些特定的值 ,一些人使用的关键字像$all$in$exists但我不确定这些可以帮助我。

我如何使我的查询工作?

写下你的查询,如下所示:

 db.smoothies.find( { "ingredients.name": "orange"} ) 

不知道MongoDB,但这是我如何用香草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" }); }))