MONGO DB UpdateOne WriteError

时间:2020-06-13 10:49:17

标签: mongodb mongodb-query

我正在使用https://docs.mongodb.com/manual/tutorial/getting-started/来开始使用Mongo。

但是在尝试更新记录时,我遇到了问题。

我尝试过的命令是:

    db.studentenrolment.insertMany([{"_id":11111111,"name":"Mary Smith","contactInfo":{"address":"20/1 Princess Highway, Caulfield East, VIC , 3145","phone":"0411111222     ","email":"msmith@monash.edu"},"enrolmentInfo":[{"unitcode":"FIT1004","year":"2013","semester":1,"mark":65,"grade":"C "},{"unitcode":"FIT1040","year":"2013","semester":2,"mark":74,"grade":"D "},{"unitcode":"FIT1040","year":"2013","semester":1,"mark":45,"grade":"N "},{"unitcode":"FIT2077","year":"2013","semester":2,"mark":74,"grade":"D "}]},
{"_id":11111115,"name":"David Dumbledore","contactInfo":{"address":"1 Queen Avenue, Caulfield East, VIC , 3145","phone":"0411111666     ","email":"dsmith@monash.edu"},"enrolmentInfo":[{"unitcode":"FIT2077","year":"2013","semester":2,"mark":45,"grade":"N "},{"unitcode":"FIT1040","year":"2013","semester":1,"mark":80,"grade":"HD"}]},
{"_id":11111116,"name":"John Chung","contactInfo":{"address":"12/1 Princess Highway, Caulfield East, VIC , 3145","phone":"0411111777     ","email":"jchung@monash.edu"},"enrolmentInfo":[{"unitcode":"FIT1004","year":"2013","semester":2,"mark":65,"grade":"C "},{"unitcode":"FIT1040","year":"2013","semester":2,"mark":80,"grade":"HD"}]}])

db.studentenrolment.update({"_id":11111111},{$push:{"enrolmentInfo"
:{"unitcode":"FIT2001","year":"2013","semester":2,"mark":0,"grade":
"-"}}})

查询在这里失败:

db.studentenrolment.updateOne (
{"_id":11111111,
"enrolmentInfo.unitcode":"FIT2001"}, 
{
$set:
{"enrolmentInfo.mark" : 87, "enrolmentInfo.grade" : "HD"
}
} )

我收到此错误:

WriteError@src/mongo/shell/bulk_api.js:458:48
Bulk/mergeBatchResults@src/mongo/shell/bulk_api.js:855:49
Bulk/executeBatch@src/mongo/shell/bulk_api.js:919:13
Bulk/this.execute@src/mongo/shell/bulk_api.js:1163:21
DBCollection.prototype.insertOne@src/mongo/shell/crud_api.js:580:17
@(shell):1:1

1 个答案:

答案 0 :(得分:0)

尝试使用$运算符进行更新。 Documentation

db.studentenrolment.updateOne (
  {"_id":11111111,
  "enrolmentInfo.unitcode":"FIT2001"}, 
  {
  $set:
  {"enrolmentInfo.$.mark" : 87, "enrolmentInfo.$.grade" : "HD"
  }
  } )