我的 mongodb 集合中存储了一个对象
{
"students" : {
"[email protected]" : {"gender" : "M", "marks" : 30},
"[email protected]" : {"gender" : "M", "marks" : 40}
}
}
我正在尝试使用以下代码片段更新 ID 为“[email protected]”的学生的分数:
db.getCollection('school').updateOne(
{
$set:{
"[email protected]": {
"gender":"M",
"marks": 40
}
}
}
)
但是它不是更新现有记录,而是创建一个新对象,如下所示:
{
"students" : {
"[email protected]" : {"gender" : "M", "marks" : 30},
"[email protected]" : {"gender" : "M", "marks" : 40},
"xyz@gmail" : {"com" : {"gender" : "M", "marks" : 40}}
}
}
所以,发生这种情况是因为 .在电子邮件 ID 中。 mongodb 有办法处理这个问题吗? 感谢对此的任何帮助,提前致谢!
我将其放入答案中,因为它不适合评论。
我鼓励您阅读此。
如果您继续在密钥中使用点,那么您将发现很难进行更新,并且会在您的应用程序中遇到很多问题。
我的建议是,如果可以的话,将结构更改为如下所示:
{
students : [
{email: "[email protected]", gender: "M", marks: 30},
{email: "[email protected]", gender: "M", marks: 40}
]
}
这可以让你做:
db.getCollection('school').updateOne({students: {$elemMatch: {email:'[email protected]'}}},
{
$set: {
"students.$": {
"email": "[email protected]",
"gender":"M",
"marks": 100
}
}
}
);