Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb is it possible to get all keys and values of object in documents in the collection?

Tags:

mongodb

Is it possible to get all keys and values of object in documents in the 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 output like :

[{
    name: 'name',
    values: ['test', 'test2', 'test3']
},
{
    name: 'size',
    values: ['S', 'm']
},
{
    name: 'color',
    values: ['red', 'green']
}
]
like image 877
rajeshpanwar Avatar asked Dec 15 '25 12:12

rajeshpanwar


1 Answers

I think you have no option to achieve your result without processing on your client side. However you can try Aggregation Framework to achieve something similar to your desired output with just a single 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}
                               }
                           ])

This will output the following:

{
   names: ['test', 'test2', 'test3'],
   sizes: ['S', 'm'],
   colors: ['red', 'green']
}
like image 186
bagrat Avatar answered Dec 19 '25 04:12

bagrat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!