我正在嘗試更新特定檔案中陣列中的多個元素,其中我有需要更新的元素的索引。
MongoDB 游樂場鏈接
假設我有一個檔案:
{
"key": 1,
"questions": [
{
"text": "first",
},
{
"text": "second",
},
{
"text": "third",
"answered": "balloon",
},
],
},
我想更新問題 2 和 3(按索引號)并在專案中添加鍵值對。
預期輸出:
{
"key": 1,
"questions": [
{
"text": "first",
},
{
"text": "second",
"answered": "second answer", //Added field
},
{
"text": "third",
"answered": "third answer", //Updated field
},
],
},
到目前為止我嘗試過的:
db.collection.update({
"key": 1,
},
{
$set: {
"questions.$[elem0].answered": "second answer",
"questions.$[elem1].answered": "third answer",
}
},
{
arrayFilters: [
{
"elem0": 1 //Trying to update index position 1
},
{
"elem1": 2 //Trying to update index position 2
}
],
})
我希望操作是原子的,而不是對我正在更新的每個專案進行多次查詢。所有專案都屬于同一檔案的嵌套陣列。
uj5u.com熱心網友回復:
$set
db.collection.update({
"key": 1
},
{
$set: {
"questions.1.answered": "second answer",
"questions.2.answered": "third answer"
}
})
mongoplayground
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/340874.html
標籤:MongoDB 猫鼬 mongodb-查询
上一篇:Linq過濾器構建器不接受過濾器型別IN的lambda
下一篇:Mongodb中的嵌套分組
