MongoDB - Aggregation - To get unique items in array

a 夏天 提交于 2019-12-30 00:37:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!