Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use field value as key name in Mongodb result

Can somebody tell me please if is possible to use field value as key in mongodb result. If I have documents like

{'code': 'xxx', 'item': 'yyy'}
{'code': 'ooo', 'item': 'eee'}

I would like to get result where code value will be the key like

{'xxx': 'yyy'}, {'ooo': 'eee'}
like image 375
Čamo Avatar asked Jan 30 '19 10:01

Čamo


1 Answers

You have to use $arrayToObject if you want to build your keys dynamically. It takes an array of k and v fields as a parameter. To make it root you can use $replaceRoot stage, try:

db.col.aggregate([
    {
        $replaceRoot: {
            newRoot: { $arrayToObject: [ [ { k: "$code", v: "$item" } ] ]}
        }
    }
])
like image 161
mickl Avatar answered Nov 06 '22 06:11

mickl