Mongo DB special values ​​group inside an array of objects

let's say I have a document model as shown below

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

Now I need to run a query with a unique pair of names and values. for example, a document has names 1 with "test" and the best values, another document has the same key (function 1 with a different value ie "guest"), so the result will be

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

so far I have tried the following query, but it returned an error at the end

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

error message

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

+4
source share
1 answer

, .

:

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

:

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

Source: https://habr.com/ru/post/1659917/


All Articles