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

问题描述:

目的

我有一个配方文件,其中包含成分(也是文件)的数组。我希望获得包含某种成分的所有食谱。如何获取包含数组中另一个文档的所有文档?

背景

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

{ 
     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,但我不确定如何将这些能帮助我。

问题

如何让我的查询工作?

+1

使用[点号](https://docs.mongodb.com/manual/core/document/#dot-notation)查询数组'的元素db.smoothies.find({“ingredients.name”:“orange”})'或['elemMatch'](https://docs.mongodb.com/v3.2/reference/operator/query/elemMatch/# ({“ingredients”:{“$ elemMatch”:{“name”:“orange”}}})' – chridam

写您的查询是这样的:

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

Polyfills:

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

+0

当答案中的一半代码是polyfills ,其余80%的代码是OP的数据,您可能需要重新考虑如何构建答案。换句话说,不要包含polyfills(___Especially__不在'代码段的HTML字段中的'