问题
Here's my MongoDB collection:
{
"_id" : ObjectId("515d8f53175b8ecb053425c2"),
"category" : "Batteries",
"products" : [
{
"brand" : "Duracell",
"item" : [
"AA",
"AAA"
]
},
{
"brand" : "Everyday",
"item" : [
"9V",
"AA",
"12V"
]
}
]
}
The output that I need is
1) Unique list of all items
{["AA", "AAA", "9V", "12V"]}
and 2. unique list of items per product
{
"category" : "Batteries",
"item": ["AA", "AAA", "9V", "12V"]
}
I'm very new to MongoDB, and I tried different aggregations functions and nothing seems to work. Please help.
回答1:
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'}}});
and
db.xyz.aggregate( {$project: {category: 1, a: '$products.item'}},
{$unwind: '$a'},
{$unwind: '$a'},
{$group: {_id: '$category', items: {$addToSet: '$a'}}});
回答2:
I am not sure what you all you have tried in the aggregation function but i thought unwind will help you to do the same , assuming you are not able to get it done , we have a map-reduce which will allow you to easily do this one . You can look into the http://docs.mongodb.org/manual/applications/map-reduce/ . It allow you to get the data in a manner you want and you can easily get the list . I think $unwind on the tags column and then $group them will always give the us the list of distinct tags as required by you in 1 and for 2nd case create $group on two key category and item which was $unwind earlier.
来源:https://stackoverflow.com/questions/15814526/mongodb-aggregation-to-get-unique-items-in-array