我想更新嵌入文档数组中的一个字段。
我的示例文件是:
db.students.insert(
{
first_name:'AA',
last_name:'BB',
cours_reussis:[{intitule:'PAI',note:0,name_school:'EPFC'}]
}
)
Run Code Online (Sandbox Code Playgroud)
我想将 的值更改name_school为“ENSA”而不是“EPFC”。
Ste*_*nie 18
如果您知道数组中嵌入文档的位置,Kalhara 的答案是正确的,但是还有一种替代方法可用于在不知道位置的情况下更新第一个匹配的数组元素。
假设您在查询条件中使用单个数组进行更新,则位置运算符 ( $)可用于引用匹配的数组元素:
db.students.update(
// Match criteria
{
first_name: 'AA',
last_name: 'BB',
'cours_reussis.name_school': 'EPFC'
},
// Update first matching array element using the positional operator ($)
{
$set: {
'cours_reussis.$.name_school': 'ENSA',
}
}
)
Run Code Online (Sandbox Code Playgroud)
小智 4
尝试这个。它可能需要根据您的其他变量进行小的修改,但我认为这会起作用:
db.students.update(
{ first_name: 'AA' },
{ $set:
{
"cours_reussis.0.name_school": 'ENSA'
}
}
)
Run Code Online (Sandbox Code Playgroud)
cours_reussis是一个数组。0 是数组索引。
供您参考:$set
| 归档时间: |
|
| 查看次数: |
37102 次 |
| 最近记录: |