MongoDB 如何更新文档数组中符合条件的第一项?
MongoDB How to update the first item that matches a condition in an array of documents?
我有一个示例文档:
{
_id: 1,
exams: [
{name: 'a', score: 2},
{name: 'b', score: 9},
{name: 'c', score: 7}
]
}
对于 [=16= 指定的文档,我需要将 exams
数组中 score
大于 7 的第一个元素的 score
设置为 10 ].
因此对于示例文档,我需要将其更新为:
{
_id: 1,
exams: [
{name: 'a', score: 2},
{name: 'b', score: 10},
{name: 'c', score: 7}
]
}
此任务的 Mongo shell 查询是什么?
使用 $gt 寻找更高的分数
updateOne({"exams.score":{ $gt: 7 }},{$set:{"exams.$.score":"10"})
我有一个示例文档:
{
_id: 1,
exams: [
{name: 'a', score: 2},
{name: 'b', score: 9},
{name: 'c', score: 7}
]
}
对于 [=16= 指定的文档,我需要将 exams
数组中 score
大于 7 的第一个元素的 score
设置为 10 ].
因此对于示例文档,我需要将其更新为:
{
_id: 1,
exams: [
{name: 'a', score: 2},
{name: 'b', score: 10},
{name: 'c', score: 7}
]
}
此任务的 Mongo shell 查询是什么?
使用 $gt 寻找更高的分数
updateOne({"exams.score":{ $gt: 7 }},{$set:{"exams.$.score":"10"})