6

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

sergiuz
  • 5,353
  • 1
  • 35
  • 51
Abdul Hameed
  • 1,008
  • 1
  • 15
  • 35

1 Answers1

8

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" ] }
sergiuz
  • 5,353
  • 1
  • 35
  • 51
  • 1
    I think he is asking tha he want just `feature 1`'s values. So Your answer is correct, just have to add `{ $match: {'features.values.name' : 'feature 1'} }` – Mohammad Kashif Sulaiman Nov 05 '16 at 12:03
  • hmm, let's see his update, than I will correct if necesarry. Tx. – sergiuz Nov 05 '16 at 12:04
  • 1
    @SergiuZaharie thanks just one thing, it returns all languages results and I want just 'en' results i also tried "{$match:{'features.language':'en'}}," but not luck – Abdul Hameed Nov 05 '16 at 12:22
  • 2
    @MohammadKashifSulaiman I just moved the above match after {$unwind: '$features'}, and it return the exact result what i need Thanks – Abdul Hameed Nov 05 '16 at 13:37