student
集合如下所示。
[{
"_id" : NumberLong(1),
"studentId" : "70133",
"subjects" : [
"Mathematics",
"Biology and Zoology"
]
},
{
"_id" : NumberLong(2),
"studentId" : "70134",
"subjects" : [
"Mathematics",
"English"
]
},
{
"_id" : NumberLong(3),
"studentId" : "70135",
"subjects" : [
"English",
"Mathematics",
"Chemistry"
]
}]);
我想编写一个查询来更新学生集合主题数组的值,如下所示:
English
必须更新为 ENG Biology
和Zoology
必须更新为 BAZ Mathematics
必须更新为 MAT Chemistry
必须更新为 CHM 更新后的文档应如下所示。我该如何实现?
[{
"_id" : NumberLong(1),
"studentId" : "70133",
"subjects" : [
"MAT",
"BAZ"
]
},
{
"_id" : NumberLong(2),
"studentId" : "70134",
"subjects" : [
"MAT",
"ENG"
]
},
{
"_id" : NumberLong(3),
"studentId" : "70135",
"subjects" : [
"ENG",
"MAT",
"CHM"
]
}]);
答案 0 :(得分:0)
这必须通过多个更新来完成,例如:
db.collection.update(
{ "subjects" : { $in : [ "Mathematics" ] } },
{ $set: { "subjects.$" : "MAT" } },
{ multi: true }
)
有关更新多个文档的更多信息,请参见此页面
如果 multi 设置为true,则db.collection.update()方法将更新所有符合条件的文档。 multi 更新操作可能会与其他读/写操作交错。
https://docs.mongodb.com/master/reference/method/db.collection.update/index.html#multi-parameter