2

Objective

I have a recipe document that contains an array of ingredients (also documents). I wish to obtain all recipes which contain a certain ingredient.

Background

Lets say I have a recipe document that looks like the following:

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

Now, lets say I have a collection with many recipes, and I want all recipes that have "oranges" as an ingredient.

What I tried

To achieve this i am trying the following using mongodb's console:

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

However, it doesn't work.

I read in other questions like Find document with array that contains a specific value that some people use keywords like $all, $in and $exists but I am unsure how these can help me.

Question

How do I make my query work?

Community
  • 1
  • 1
Flame_Phoenix
  • 16,489
  • 37
  • 131
  • 266
  • 1
    Use the [dot notation](https://docs.mongodb.com/manual/core/document/#dot-notation) to query the elements of an array `db.smoothies.find({ "ingredients.name": "orange" })` or [`$elemMatch`](https://docs.mongodb.com/v3.2/reference/operator/query/elemMatch/#array-of-embedded-documents) as `db.smoothies.find({ "ingredients": { "$elemMatch": { "name": "orange" } } })` – chridam Nov 07 '16 at 09:46

2 Answers2

2

Write your query like this:

db.smoothies.find( { "ingredients.name": "orange"} )
Simran
  • 2,364
  • 1
  • 12
  • 19
-1

Don't know about MongoDB, but this is how i would do it with 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 if needed:

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

Emil S. Jørgensen
  • 6,216
  • 1
  • 15
  • 28
  • When half the code in your answer is polyfills, and 80% of the remaining code is the OP's data, you may want to reconsider how you're structuring your answer. In other words, don't include the polyfills (___Especially___ not in a ` – Cerbrus Nov 07 '16 at 09:51