How to use field value as key name in Mongodb result

后端 未结 2 786
没有蜡笔的小新
没有蜡笔的小新 2020-12-11 03:23

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

{\'code\': \'xxx\', \'item\': \'yyy\'}
{\'         


        
相关标签:
2条回答
  • 2020-12-11 04:21

    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" } ] ]}
            }
        }
    ])
    
    0 讨论(0)
  • 2020-12-11 04:25

    I don't think thats possible. Mongo leaves the interpretation of the result to the application. Thats why mongodb is a shema-less database.

    0 讨论(0)
提交回复
热议问题