How to use field value as key name in Mongodb result

ぐ巨炮叔叔 提交于 2019-12-07 05:56:56

问题


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'}
{'code': 'ooo', 'item': 'eee'}

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

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

回答1:


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" } ] ]}
        }
    }
])



回答2:


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



来源:https://stackoverflow.com/questions/54438528/how-to-use-field-value-as-key-name-in-mongodb-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!