我想重命名嵌套数组中对象本身内的字段。例如,我想在本文档中将所有标记m2重命名为m6:
{
"_id": 1,
"tagsGroup": [
{
"id": "1234",
"tags": {
"m1": 1,
"m2": 2
}
},
{
"id": "456",
"tags": {
"m3": 1,
"m2": 2
}
},
{
"id": "1234",
"tags": {
"m4": 2,
"m5": 2
}
},
]
}这是我目前的工作状况:
db.collection.update({},
{
"$set": {"tagsGroup.$[tGp].tags.m6": "$tagsGroup.$[tGp].tags.m2"},
"$unset": {"tagsGroup.$[tGp].tags.m2": ""}
},
{
arrayFilters: [{"tGp.tags.m2": {$exists: 1}}],
multi: true}
)不幸的是,$tagsGroup.$[tGp].tags.m6没有被解释。你们有办法吗?
谢谢!
发布于 2021-01-29 08:33:50
可能类似于这个问题数组中的MongoDB重命名数据库字段,
用一个命令来重命名数组中的字段没有直接的方法。您可以从使用聚合管道进行更新 v4.2开始尝试MongoDB,
$map迭代tagsGroup数组的循环$map迭代tags对象的循环后,使用$objectToArray转换成数组,它将以k和v格式返回。$replaceOne将替换查找字段上的特定字符串,这是从MongoDB v4.4开始的$arrayToObject将第二个$map返回的tags数组转换为对象格式$mergeObjects将当前对象与更新的tags对象合并db.collection.update(
{ "tagsGroup.tags.m2": { $exists: true } },
[{
$set: {
tagsGroup: {
$map: {
input: "$tagsGroup",
in: {
$mergeObjects: [
"$$this",
{
tags: {
$arrayToObject: {
$map: {
input: { $objectToArray: "$$this.tags" },
in: {
k: {
$replaceOne: {
input: "$$this.k",
find: "m2",
replacement: "m6"
}
},
v: "$$this.v"
}
}
}
}
}
]
}
}
}
}
}],
{ multi: true }
)https://stackoverflow.com/questions/65950455
复制相似问题