MongoDB的:我如何更新阵列中有一个子元素,通过阵列中的索引引用? [英] MongoDB: How do I update a single subelement in an array, referenced by the index within the array?

查看:87
本文介绍了MongoDB的:我如何更新阵列中有一个子元素,通过阵列中的索引引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图更新包含在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 ... }
  ]
}

好像查询应该是这样的:(同样,伪code)

Seems like the query should be something like this: (Again, pseudocode)

db.my_collection.update(
  {_id: ObjectId(document_id), my_array.1 : 1 },
  {my_array.$.content: NEW content B }
)

但是,这并不正常工作。我已经花了太多的时间搜索MongoDB的文档,并在此语法尝试不同的变化(例如,使用$片等),我找不到如何完成这种更新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. Please help!

推荐答案

正如预期的那样,查询很​​容易,一旦你知道怎么办。这里的语法,在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆