Mongodb can get all keys and values โ€‹โ€‹of an object in documents in a collection?

Is it possible to get all the keys and values โ€‹โ€‹of an object in documents in a collection?

I have a collection in mongo db with structure like

[{
    _id: '55534c2e2750b4394debedd2',
    selected_options: {
        name: 'test',
        size: 'S',
        color: 'red'
    }
},
 {
    _id: '55534c2e2750b4394debedd3',
    selected_options: {
        name: 'test2',
        size: 'S',
        color: 'red'
    }

},
{
    _id: '55534e087f01fa2a4d30f7f5',
    selected_options: {
        name: 'test3',
        size: 'm',
        color: 'green'
    }
}
........
]

      

how can i get the output like:

[{
    name: 'name',
    values: ['test', 'test2', 'test3']
},
{
    name: 'size',
    values: ['S', 'm']
},
{
    name: 'color',
    values: ['red', 'green']
}
]

      

+3


source to share


2 answers


I think there is no way for you to achieve the result without processing on your client side. However, you can try the Aggregation Framework to achieve something similar to your desired result with just one query.

db.yourCollection.aggregate([
                               {$group: 
                                  {
                                     _id: null,
                                     names: {$addToSet: '$selected_options.name'},
                                     sizes: {$addToSet: '$selected_options.size'},
                                     colors: {$addToSet: '$selected_options.color'},
                                  }
                               },
                               {$project:
                                  {_id: 0, names: 1, colors: 1, sizes: 1}
                               }
                           ])

      



As a result, you will get the following:

{
   names: ['test', 'test2', 'test3'],
   sizes: ['S', 'm'],
   colors: ['red', 'green']
}

      

+1


source


Another option: distinct () for each field.



See the sample output on the documentation page.

0


source







All Articles