我有以下文件:
{_id: '4eb79ee1e60fc603788e7259',
Name: 'name',
Subsidiaries: [
{ _id: '4eb79eeae60fc603788e7271',
Location: 'location1'},
{ _id: 'subid2',
Location: 'location2'},
]}
我想更新子公司的位置:
db.Departments.update({ "_id" : ObjectId("4eb79ee1e60fc603788e7259"), "Subsidiaries._id" : ObjectId("4eb79eeae60fc603788e7271") }, { "$set" : { "Subsidiaries.Location" : "City" } })
但MongoDb返回错误:“无法使用字符串字段名称附加到数组[Location]”
答案 0 :(得分:16)
您必须使用$ poistional operator来更新嵌入的文档,
db.Departments.update(
{ "_id" : ObjectId("4eb79ee1e60fc603788e7259"),
"Subsidiaries._id" : ObjectId("4eb79eeae60fc603788e7271") },
{ "$set" : { "Subsidiaries.$.Location" : "City" } }
)