MongoDB:如何更新数组中的嵌入文档

1gn*_*ter 6 mongodb

我有以下文件:

{_id: '4eb79ee1e60fc603788e7259',
Name: 'name', 
Subsidiaries: [
  { _id: '4eb79eeae60fc603788e7271',
   Location: 'location1'},
  { _id: 'subid2',
   Location: 'location2'},
]}
Run Code Online (Sandbox Code Playgroud)

我想更新子公司的位置:

db.Departments.update({ "_id" : ObjectId("4eb79ee1e60fc603788e7259"), "Subsidiaries._id" : ObjectId("4eb79eeae60fc603788e7271") }, { "$set" : { "Subsidiaries.Location" : "City" } })
Run Code Online (Sandbox Code Playgroud)

但MongoDb返回错误:"无法使用字符串字段名称[Location]附加到数组

Ram*_*Vel 16

您必须使用$ poistional运算符来更新嵌入的文档,

db.Departments.update(
     { "_id" : ObjectId("4eb79ee1e60fc603788e7259"),
       "Subsidiaries._id" : ObjectId("4eb79eeae60fc603788e7271") },
     { "$set" : { "Subsidiaries.$.Location" : "City" } }
 )
Run Code Online (Sandbox Code Playgroud)

  • 在我的情况下,这说,**不能使用字符串字段名[$]**附加到数组,虽然我可以看到上面的文档和我的文档是完全相同的. (4认同)