Flame_Phoenix Flame_Phoenix - 1 year ago 55
Javascript Question

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


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


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
but I am unsure how these can help me.


How do I make my query work?

Sam Sam
Answer Source

Write your query like this:

db.smoothies.find( { "ingredients.name": "orange"} )
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download