我有以下文件:
{_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]附加到数组
您必须使用$ poistional运算符来更新嵌入的文档,
db.Departments.update( { "_id" : ObjectId("4eb79ee1e60fc603788e7259"), "Subsidiaries._id" : ObjectId("4eb79eeae60fc603788e7271") }, { "$set" : { "Subsidiaries.$.Location" : "City" } } )