【问题标题】:How to get all docs which contain another doc in an array?如何获取包含数组中另一个文档的所有文档?
【发布时间】: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" })$elemMatchdb.smoothies.find({ "ingredients": { "$elemMatch": { "name": "orange" } } })

标签: javascript arrays node.js mongodb mongoose


【解决方案1】:

这样写你的查询:

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

【讨论】:

    【解决方案2】:

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

    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

    【讨论】:

    • 当你的答案中有一半的代码是 polyfills,而剩余代码的 80% 是 OP 的数据时,你可能需要重新考虑如何构建你的答案。换句话说,不要包含 polyfill(特别是不在 sn-p 的 HTML 字段中的 <script> 标记中)。如果您认为确实有必要,只需链接到它们即可。
    猜你喜欢
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-26
    • 2013-07-28
    • 2022-12-23
    • 1970-01-01
    • 2017-03-16
    相关资源
    最近更新 更多