mongodbphp-mongodbmongodb-query

MongoDB - Aggregation - To get unique items in array


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.


Solution

  • 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'}}});