【问题标题】:MongoDB: how to update embeded documents in arrayMongoDB:如何更新数组中的嵌入文档
【发布时间】:2014-12-16 22:24:40
【问题描述】:

我有以下文件:

{_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返回错误:“can't append to array using string field name [Location]”

【问题讨论】:

    标签: mongodb


    【解决方案1】:

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

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

    【讨论】:

    • 在我的情况下,这表示 can't append to array using string field name [$] ,尽管我可以看到上面的文档和我的文档完全相同。
    猜你喜欢
    • 2017-06-05
    • 2017-04-28
    • 1970-01-01
    • 2016-08-13
    • 1970-01-01
    • 1970-01-01
    • 2013-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多