MongoDB:如何更新由数组中的索引引用的数组中的单个子元素? [英] MongoDB: How do I update a single subelement in an array, referenced by the index within the array?
问题描述
我正在尝试更新 mongodb 文档中包含在数组中的单个子元素.我想使用它的数组索引引用该字段(数组中的元素没有任何我可以保证将是唯一标识符的字段).看起来这应该很容易做到,但我无法弄清楚语法.
I'm trying to update a single subelement contained within an array in a mongodb document. I want to reference the field using its array index (elements within the array don't have any fields that I can guarantee will be unique identifiers). Seems like this should be easy to do, but I can't figure out the syntax.
这是我想在伪 json 中做的事情.
Here's what I want to do in pseudo-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 ... }
]
}
看起来查询应该是这样的:
Seems like the query should be something like this:
//pseudocode
db.my_collection.update(
{_id: ObjectId(document_id), my_array.1 : 1 },
{my_array.$.content: NEW content B }
)
但这行不通.我花了很长时间搜索 mongodb 文档,并尝试了这种语法的不同变体(例如,使用 $slice
等).我找不到有关如何在 MongoDB 中完成此类更新的任何明确说明.
But this doesn't work. I've spent way too long searching the mongodb docs, and trying different variations on this syntax (e.g. using $slice
, etc.). I can't find any clear explanation of how to accomplish this kind of update in MongoDB.
推荐答案
正如预期的那样,一旦您知道如何进行,查询就会很容易.这是python中的语法:
As expected, the query is easy once you know how. Here's the syntax, in python:
db["my_collection"].update(
{ "_id": ObjectId(document_id) },
{ "$set": { 'documents.'+str(doc_index)+'.content' : new_content_B}}
)
这篇关于MongoDB:如何更新由数组中的索引引用的数组中的单个子元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!