在mongodb中,我有一个结构文档:
{
"phone":"123",
"friends": {
"contacts":{
"234":2,
"345":5
}
}
}我希望输出看起来像:
{
"123": {
"234":2,
"345":5
}
}我要寻找多个解决方案。看上去不像是找到解决办法。
发布于 2018-11-26 10:52:35
您可以使用$arrayToObject创建自定义键(以k-v对数组作为参数),然后可以使用$replaceRoot获取自定义根对象,尝试:
db.collection.aggregate([
{
$match: {
phone: { $exists: true },
"friends.contacts": { $exists: true }
}
},
{
$addFields: {
array: [{
k: "$phone",
v: "$friends.contacts"
}]
}
},
{
$replaceRoot: {
newRoot: { $arrayToObject: "$array" }
}
}
])https://stackoverflow.com/questions/53476592
复制相似问题