Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 812
Abdul Hameed Avatar asked Nov 05 '16 11:11

Abdul Hameed


1 Answers

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" ] }
like image 158
sergiuz Avatar answered Nov 15 '22 04:11

sergiuz