mongo 更新数组里的某个字段
在MongoDB中,我们经常会遇到需要更新数组中某个字段的情况。这个问题可能会涉及到更新嵌套在数组中的字段,或者是更新数组中的指定元素。在本文中,我们将详细介绍如何在MongoDB中更新数组中的某个字段。
更新数组中的指定元素
假设我们有以下的文档结构:
{
"_id": 1,
"name": "Alice",
"scores": [
{ "subject": "Math", "score": 80 },
{ "subject": "English", "score": 90 },
{ "subject": "Science", "score": 85 }
]
}
现在我们想要将”Alice”的”Math”分数更新为90。我们可以使用以下的代码来实现:
db.students.updateOne(
{ "_id": 1, "scores.subject": "Math" },
{ "set": { "scores..score": 90 } }
)
上面的代码中,我们使用了updateOne
方法来更新指定条件的文档。在更新的条件中,我们使用了"scores.subject": "Math"
来匹配包含”Math”科目的成绩。而在更新的操作中,我们使用了"set": { "scores..score": 90 }
来更新找到的第一个匹配结果中”Math”科目的分数为90。
接下来我们来看看更新后的文档:
{
"_id": 1,
"name": "Alice",
"scores": [
{ "subject": "Math", "score": 90 },
{ "subject": "English", "score": 90 },
{ "subject": "Science", "score": 85 }
]
}
可以看到”Alice”的”Math”分数已经更新为90了。
更新数组中所有元素
如果我们想要更新所有成绩中的分数加上10分,我们可以使用以下的代码:
db.students.updateMany(
{},
{ "inc": { "scores.[].score": 10 } }
)
上面的代码中,我们使用了updateMany
方法来更新所有的文档。在更新的操作中,我们使用了"inc": { "scores.[].score": 10 }
来将所有成绩中的分数加上10分。
更新后的文档如下:
{
"_id": 1,
"name": "Alice",
"scores": [
{ "subject": "Math", "score": 100 },
{ "subject": "English", "score": 100 },
{ "subject": "Science", "score": 95 }
]
}
可以看到所有成绩的分数都加上了10分。
更新嵌套数组中的字段
有时,我们可能会遇到更新嵌套在数组中的字段的情况。例如,我们有以下的文档结构:
{
"_id": 1,
"name": "Bob",
"results": [
{
"semester": "Spring",
"scores": [
{ "subject": "Math", "score": 85 },
{ "subject": "English", "score": 90 }
]
},
{
"semester": "Fall",
"scores": [
{ "subject": "Math", "score": 80 },
{ "subject": "English", "score": 88 }
]
}
]
}
现在我们想要将”Bob”在”Spring”学期的”Math”分数更新为90。我们可以使用以下的代码来实现:
db.students.updateOne(
{ "_id": 1, "results.semester": "Spring", "results.scores.subject": "Math" },
{ "set": { "results..scores.$[elem].score": 90 } },
{ "arrayFilters": [ { "elem.subject": "Math" } ] }
)
上面的代码中,我们使用了"results.scores.subject": "Math"
来匹配包含”Math”科目的成绩。而在"arrayFilters"
中,我们使用了{ "elem.subject": "Math" }
来匹配包含”Math”科目的具体成绩。
接下来我们来看看更新后的文档:
{
"_id": 1,
"name": "Bob",
"results": [
{
"semester": "Spring",
"scores": [
{ "subject": "Math", "score": 90 },
{ "subject": "English", "score": 90 }
]
},
{
"semester": "Fall",
"scores": [
{ "subject": "Math", "score": 80 },
{ "subject": "English", "score": 88 }
]
}
]
}
可以看到”Bob”在”Spring”学期的”Math”分数已经更新为90了。