我正在尝试更新 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 中完成这种更新的明确解释。
最佳答案
正如预期的那样,一旦您知道如何查询,查询就很容易了。这是python中的语法:
db["my_collection"].update(
{ "_id": ObjectId(document_id) },
{ "$set": { 'documents.'+str(doc_index)+'.content' : new_content_B}}
)
https://stackoverflow.com/questions/11372065/