如何在Mongodb结果中将字段值用作键名 [英] How to use field value as key name in Mongodb result
本文介绍了如何在Mongodb结果中将字段值用作键名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人可以告诉我在mongodb结果中是否可以使用字段值作为键.如果我有
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'}
推荐答案
您必须使用 $ arrayToObject (如果要动态构建密钥).它使用k
和v
字段的数组作为参数.要使其扎根,您可以使用 $ replaceRoot 阶段,尝试:
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" } ] ]}
}
}
])
这篇关于如何在Mongodb结果中将字段值用作键名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文