考虑以下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" ]
Ric*_*zaк 10
以下查询将为您提供裸列表减去任何重复项:
db.recipes.aggregate([{$unwind:"$ingredients"},{$group:{_id:"$ingredients.name"}}])
Run Code Online (Sandbox Code Playgroud)
添加数量需要做更多的工作.如果单独指定数量单位,将会更容易.
| 归档时间: |
|
| 查看次数: |
7728 次 |
| 最近记录: |