我有以这种方式存储的mongodb数据
db.orders.insert( { _id: ObjectId().str, name: "admin", status: "online",catalog : [
{
"objectid" : ObjectId().str,
"message" : "sold",
"status" : "open"
}
]})
我试图以这种方式更新db.orders.update({"_id":"5703b86df3d607cb5fa75ff3"},{$set: {"catalog.message": "added to cart"}})
这是我得到的错误消息
> db.orders.update({"_id":"5703b86df3d607cb5fa75ff3"},{$set: {"catalog.message": "added to cart"}})
WriteResult({
"nMatched" : 0,
"nUpserted" : 0,
"nModified" : 0,
"writeError" : {
"code" : 16837,
"errmsg" : "cannot use the part (catalog of catalog.message) to traverse the element ({catalog: [ { objectid: \"5703b86df3d607cb5fa75ff4\", message: \"sold\", status: \"open\" } ]})"
}
})
如何更新此记录?。
答案 0 :(得分:2)
根据MongoDB's Examples,您应该提供要更新的数组中Object的索引。由于您想要更新第一个对象,即索引0处数组中的对象,请使用:
db.orders.update(
{"_id":"5703b86df3d607cb5fa75ff3"},
{$set: {"catalog.0.message": "added to cart"}});