MongoDB:如何更新数组中的单个子元素(由数组中的索引引用)?

我正在尝试更新mongodb文档中数组中包含的单个子元素。我想使用其数组索引来引用该字段(数组中的元素没有任何我可以保证将是唯一标识符的字段)。看起来这样应该很容易,但是我无法弄清楚语法。


这是我要在伪json中执行的操作。


之前:


{

  _id : ...,

  other_stuff ... ,

  my_array : [

    { ... old content A ... },

    { ... old content B ... },

    { ... old content C ... }

  ]

}

后:


{

  _id : ...,

  other_stuff ... ,

  my_array : [

    { ... old content A ... },

    { ... NEW content B ... },

    { ... old content C ... }

  ]

}

好像查询应该是这样的:


//pseudocode

db.my_collection.update(

  {_id: ObjectId(document_id), my_array.1 : 1 },

  {my_array.$.content: NEW content B }

)

但这是行不通的。我花了太多时间搜索mongodb文档,并尝试对此语法进行不同的修改(例如,使用$slice等等)。我找不到任何有关如何在MongoDB中完成这种更新的明确解释。


月关宝盒
浏览 1275回答 3
3回答

慕桂英3389331

不出所料,查询就很容易。这是python中的语法:db["my_collection"].update(    { "_id": ObjectId(document_id) },    { "$set": { 'documents.'+str(doc_index)+'.content' : new_content_B}})
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

MongoDB