【问题标题】:MONGO DB UpdateOne WriteErrorMONGO DB UpdateOne WriteError
【发布时间】:2020-10-03 02:55:47
【问题描述】:

我正在使用 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

【问题讨论】:

    标签: mongodb mongodb-query


    【解决方案1】:

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

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

    【讨论】:

    • 知道了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2018-08-29
    • 2019-11-22
    • 1970-01-01
    • 2022-12-20
    • 2017-10-30
    • 2015-01-25
    • 1970-01-01
    • 2023-02-21
    相关资源
    最近更新 更多