如何从 mongodb 中的另一个子字段元素更新子字段元素?
How to update a subfield element from another subfield element in mongodb?
想象这个数据结构:
{
_id: 1
...
sections: [
{
Title: 'hello world',
Title2: '',
},
{
Title: 'goodbye',
Title2: ''
}
]
}
我需要更新 Title 中的所有 Title2。
我试过类似的东西:
db...update(
{ },
[{ $set:
{
"sections.Title2": "sections.Title",
}
}])
但没有成功。还尝试使用 updateMany 和一些变体,如 sections.$.Title2.
感谢您的帮助
你可以通过更新+聚合pipleine(mongod 4.2+) & $map如下:
db.collection.update({
sections: {
$exists: true
}
},
[
{
$addFields: {
"sections": {
$map: {
input: "$sections",
as: "s",
in: {
"Title": "$$s.Title",
"Title2": "$$s.Title"
}
}
}
}
}
],
{
multi: true
})
解释:
查找并替换现有部分,将 Title2 的必要数组值映射到 Title。
添加选项 {multi:true} 以更新集合中的所有文档
改进版本2:
db.collection.update({
sections: {
$exists: true
}
},
[
{
$addFields: {
"sections": {
$map: {
input: "$sections",
as: "s",
in: {
$mergeObjects: [
"$$s",
{
"Title2": "$$s.Title"
}
]
}
}
}
}
}
],
{
multi: true
})
解释:
在此版本中,您将更改的值与子文档合并,因此您无需添加所有其他将要更改的字段。
想象这个数据结构:
{
_id: 1
...
sections: [
{
Title: 'hello world',
Title2: '',
},
{
Title: 'goodbye',
Title2: ''
}
]
}
我需要更新 Title 中的所有 Title2。
我试过类似的东西:
db...update(
{ },
[{ $set:
{
"sections.Title2": "sections.Title",
}
}])
但没有成功。还尝试使用 updateMany 和一些变体,如 sections.$.Title2.
感谢您的帮助
你可以通过更新+聚合pipleine(mongod 4.2+) & $map如下:
db.collection.update({
sections: {
$exists: true
}
},
[
{
$addFields: {
"sections": {
$map: {
input: "$sections",
as: "s",
in: {
"Title": "$$s.Title",
"Title2": "$$s.Title"
}
}
}
}
}
],
{
multi: true
})
解释: 查找并替换现有部分,将 Title2 的必要数组值映射到 Title。 添加选项 {multi:true} 以更新集合中的所有文档
改进版本2:
db.collection.update({
sections: {
$exists: true
}
},
[
{
$addFields: {
"sections": {
$map: {
input: "$sections",
as: "s",
in: {
$mergeObjects: [
"$$s",
{
"Title2": "$$s.Title"
}
]
}
}
}
}
}
],
{
multi: true
})
解释: 在此版本中,您将更改的值与子文档合并,因此您无需添加所有其他将要更改的字段。