在MongoDB文档中获取唯一的嵌入式/嵌套对象的列表

问题描述:

考虑以下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.)

是否可以在MongoDB中创建这样的查询,如果是这样,该查询将是什么?还是需要我为成分"创建一个单独的集合?

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

以下查询将为您提供裸露的名单,减去任何重复项:

The following query would give you the bare list minus any duplicates:

db.recipes.aggregate([{$unwind:"$ingredients"},{$group:{_id:"$ingredients.name"}}])

增加数量将需要更多的工作.如果单独指定数量单位会更容易.

More work would be necessary to add the quantities. It would be easier if the unit for the quantities was specified separately.