在mongo中,项目值作为键,嵌入文档作为值

  • 本文关键字:文档 mongo 项目 mongodb
  • 更新时间 :
  • 英文 :


在mongodb中,我有一个结构文档:

{
"phone":"123",
"friends": {
"contacts":{
"234":2,
"345":5
}
}
}

我希望输出看起来像:

{
"123": {
"234":2,
"345":5
}
}

我一直在寻找多种解决方案。似乎没有得到解决方案。

您可以使用$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" }
}
}
])

最新更新