Search code examples
mongodbmongodb-queryaggregation-frameworkmongodb-aggregation

Mongo DB distinct values group within array of objects


let say I have a document model like below

{
"_id" : "QggaecdDWkZzMmmM8",
"features" : [ 
    {
        "language" : "en",
        "values" : [ 
            {
                "name" : "feature 1",
                "values" : [ 
                    "test", 
                    "best"
                ]
            }, 
            {
                "name" : "feature2",
                "values" : [ 
                    "guest", 
                    "nest"
                ]
            }
        ]
    }
}

Now i need to run query with return the unique name and value pair of features. like a document have name featues 1 with "test" and best values, the other document have the same key (feature 1 with different value i.e "guest"), so the result will be

name: featuer 1 
values: [test, best and guest]

till now i tried the following query but it return error at the end

db.getCollection('products').aggregate(
{$unwind: '$features'},
{$group: 
{_id: "$features.values.name"},
name: {$addToSet: '$name'}
})

the error message is

exception: A pipeline stage specification object must contain exactly one field


Solution

  • name field should be inside group stage, that's why you have error.

    Try this query:

    db.getCollection('products').aggregate([
        {
            $unwind: '$features'
        },
        {
            $unwind: '$features.values'
        },
        {
            $unwind: '$features.values.values'
        },
        {
            $group: {
                _id: "$features.values.name",
                values: {$addToSet: '$features.values.values'}
            },
        }
    ])
    

    Result:

    { "_id" : "feature2", "values" : [ "nest", "guest" ] }
    { "_id" : "feature 1", "values" : [ "best", "test" ] }