Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a list of unique embedded/nested objects in a MongoDB document

Tags:

mongodb

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"?

like image 267
Stanley Avatar asked Nov 12 '13 07:11

Stanley


People also ask

How do I find nested objects in MongoDB?

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.

How do I query unique records in MongoDB?

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.

How do I query an array of objects in MongoDB?

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.


1 Answers

Use distinct to find an array of distinct values for ingredients.name

db.recipes.distinct('ingredients.name')

yields [ "butter", "cheese", "noodles", "flour", "sugar", "water" ]

like image 142
c.P.u1 Avatar answered Oct 15 '22 01:10

c.P.u1