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

Sta*_*ley 10 mongodb

考虑以下MongoDB"recipes"集合:

{
  "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" },
  ]
}
Run Code Online (Sandbox Code Playgroud)

我希望写一个查询来生成购买物品的"购物清单"以制作所有食谱.所以我基本上想要归还"面条","黄油","奶酪","糖","黄油","面粉","水"等成分.我不想要重复.(糖和黄油,例如出现在多个配方中,但我只想返回一次,即没有重复.)

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

c.P*_*.u1 27

使用distinct找到不同值的数组ingredients.name

db.recipes.distinct('ingredients.name')
Run Code Online (Sandbox Code Playgroud)

产量 [ "butter", "cheese", "noodles", "flour", "sugar", "water" ]

  • 这是最好的解决方案 - ) (3认同)

Ric*_*zaк 10

以下查询将为您提供裸列表减去任何重复项:

db.recipes.aggregate([{$unwind:"$ingredients"},{$group:{_id:"$ingredients.name"}}])
Run Code Online (Sandbox Code Playgroud)

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

  • 我接受这个答案,因为它给了我我所需要的,但是聚合的使用也使得可以在"成分"(使用"$ first"运算符)中包含更多字段,而不仅仅是名称.(如果我愿意,它甚至可以汇总"数量"字段.)所以这个答案更有力,是帮助我解决问题的答案.cPu1的答案是更简单的,如果我只想要返回"名称"(如我的问题中所述),所以我也支持这个答案. (2认同)