MongoDB-聚合-获取数组中的唯一项 [英] MongoDB - Aggregation - To get unique items in array
本文介绍了MongoDB-聚合-获取数组中的唯一项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的MongoDB集合:
Here's my MongoDB collection:
{
"_id" : ObjectId("515d8f53175b8ecb053425c2"),
"category" : "Batteries",
"products" : [
{
"brand" : "Duracell",
"item" : [
"AA",
"AAA"
]
},
{
"brand" : "Everyday",
"item" : [
"9V",
"AA",
"12V"
]
}
]
}
我需要的输出是
1)所有项目的唯一列表
1) Unique list of all items
{["AA", "AAA", "9V", "12V"]}
和 2.每个产品的唯一商品列表
and 2. unique list of items per product
{
"category" : "Batteries",
"item": ["AA", "AAA", "9V", "12V"]
}
我是MongoDB的新手,我尝试了不同的聚合函数,但似乎没有任何效果.请帮忙.
I'm very new to MongoDB, and I tried different aggregations functions and nothing seems to work. Please help.
推荐答案
再尝试几次后,我解决了这个问题.这是命令:
After few more tries, I had solved this. Here's the commands:
db.xyz.aggregate( {$project: {a: '$products.item'}},
{$unwind: '$a'},
{$unwind: '$a'},
{$group: {_id: 'a', items: {$addToSet: '$a'}}});
和
db.xyz.aggregate( {$project: {category: 1, a: '$products.item'}},
{$unwind: '$a'},
{$unwind: '$a'},
{$group: {_id: '$category', items: {$addToSet: '$a'}}});
这篇关于MongoDB-聚合-获取数组中的唯一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文