Consider the following MongoDB "recipes" collection:
{
"title" : "Macaroni and Cheese",
"ingredients" : [
{ "name" : "noodles", "qty" : "2 c" },
{ "name" : "butter", "qty" : "2 tbl" },
{ "name" : "cheese", "qty" : "1 c" },
]
},
{
"title" : "Pound Cake",
"ingredients" : [
{ "name" : "sugar", "qty" : "1 lb" },
{ "name" : "butter", "qty" : "1 lb" },
{ "name" : "flour", "qty" : "1 lb" },
]
},
{
"title" : "Dough",
"ingredients" : [
{ "name" : "water", "qty" : "2 c" },
{ "name" : "butter", "qty" : "8 tbl" },
{ "name" : "flour", "qty" : "1 lb" },
]
}
I wish to write a query to generate a "shopping list" of items to buy to make all the recipes. So I basically want to return the ingredients "noodles", "butter", "cheese", "sugar", "butter", "flour", "water". I don't want duplicates. (Sugar and butter, for example appear in more than one recipe, but I only want to return them once, i.e. no duplicates.)
Is it possible to create such a query in MongoDB and if so, what would this query be? Or would it necessitate me to create a separate collection for "ingredients"?
Accessing embedded/nested documents – In MongoDB, you can access the fields of nested/embedded documents of the collection using dot notation and when you are using dot notation, then the field and the nested field must be inside the quotation marks.
To get unique values and ignore duplicates, use distinct() in MongoDB. The distinct() finds the distinct values for a specified field across a single collection and returns the results in an array.
To search the array of object in MongoDB, you can use $elemMatch operator. This operator allows us to search for more than one component from an array object.
Use distinct
to find an array of distinct values for ingredients.name
db.recipes.distinct('ingredients.name')
yields [ "butter", "cheese", "noodles", "flour", "sugar", "water" ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With