gpt4 book ai didi

mongodb - 更新嵌套文档中的键

转载 作者:行者123 更新时间:2023-12-04 02:28:19 25 4
gpt4 key购买 nike

我想更新存储在 MongoDB 集合中的以下文档中对象“值”的键:

{
"data": {
"name": "Doe",
"values": {
"AA_Avg": 13,
"BB_Avg": 19,
"CC_Avg": 18
}
}
}

让它看起来像这样:

{
"data": {
"name": "Doe",
"values": {
"AA_MT": 13,
"BB_MT": 19,
"CC_MT": 18
}
}
}

最佳答案

您可以使用的动态更新update with aggregation pipeline从 MongoDB 4.2 开始,

第一种方法:使用$rpelaceOne ,

  • $objectToArraydata.values 从对象转换为 k 和 v 格式的数组
  • $map 迭代上述转换数组的循环
  • $replaceOne 将根据输入和替换替换字符串
  • $arrayToObject 返回从数组到对象的转换
db.collection.update({},
[{
$set: {
"data.values": {
$arrayToObject: {
$map: {
input: { $objectToArray: "$data.values" },
in: {
k: {
$replaceOne: {
input: "$$this.k",
find: "Avg",
replacement: "MT"
}
},
v: "$$this.v"
}
}
}
}
}
}
])

Playground


第二种方法:使用$split$arrayElemAt$concat

Playground

关于mongodb - 更新嵌套文档中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65830503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com