想象這個資料結構:
{
_id: 1
...
sections: [
{
Title: 'hello world',
Title2: '',
},
{
Title: 'goodbye',
Title2: ''
}
]
}
我需要從 Title 更新所有 Title2。
我試過這樣的事情:
db...update(
{ },
[{ $set:
{
"sections.Title2": "sections.Title",
}
}])
但沒有成功。還嘗試了 updateMany 和一些變體,如section.$.Title2。
感謝您的任何幫助
uj5u.com熱心網友回復:
您可以通過 update aggregation 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} 以更新集合中的所有檔案
操場
uj5u.com熱心網友回復:
您可以$像這樣使用運算子:
db.collection.update({},
{
"$set": {
"sections.$[].title2": "sections.Title"
}
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/449260.html
上一篇:如何創建一個帶有迭代器的結構?
下一篇:當我使用應用程式時,使用supertest和Jest測驗Express、MongoDB和TypeScript失敗
