mongodb - 项目值作为键,嵌入文档作为 mongo 中的值
问题描述
在 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" }
}
}
])
推荐阅读
- python - 用于计算非零或一值的自定义 keras 损失函数
- azure - 使用自动生成的 SAS 令牌启用 Linux 诊断扩展的 Azure ARM 模板
- angular - 从 v5.2 到 v6.1 而不是 v7.x 的 Angular 更新
- python - PYTHON2 失败的构建轮 PyAudio 和 PortAudio
- c# - 即使函数失败,也会创建输出 blob
- excel - Excel 宏循环 - 每列删除重复项
- ios - Xcode 10.1 在尝试将应用程序侧加载到带有 iOS 12.1 的设备后未能创建配置文件
- php - 使用 XmlReader 验证大型 XML
- sql - 表值参数可以是临时的吗
- javascript - 如何在节点中获取多个图像并在浏览器中显示