Flame_Phoenix
Flame_Phoenix

Reputation: 17564

How to get all docs which contain another doc in an array?

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?

Upvotes: 2

Views: 76

Answers (2)

Emil S. Jørgensen
Emil S. Jørgensen

Reputation: 6366

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

Upvotes: -1

Simran
Simran

Reputation: 2810

Write your query like this:

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

Upvotes: 2

Related Questions