如何更新MongoDB中特定文档的数组内特定嵌入文档的值? [英] How to update value of specific embedded document, inside an array, of a specific document in MongoDB?

查看:66
本文介绍了如何更新MongoDB中特定文档的数组内特定嵌入文档的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文档中具有以下结构:

I have the following structure in my document:

{
  _id : ObjectId("43jh4j343j4j"), 
  array : [
            { 
              _arrayId : ObjectId("dsd87dsa9d87s9d7"),
              someField : "something",
              someField2 : "something2"
            },
            { 
              _arrayId : ObjectId("sds9a0d9da0d9sa0"),
              someField : "somethingElse",
              someField2 : "somethingElse2"
            }
   ]
 }

我想更新 someField someField2 ,但仅针对数组中的一项,即与 _arrayId 相匹配的一项(例如,_arrayId : ObjectId("dsd87dsa9d87s9d7");仅适用于此文档(例如_id : ObjectId("43jh4j343j4j")),没有其他内容.

I want to update someField and someField2 but only for one of the items in the array, the one that matches _arrayId (e.g. _arrayId : ObjectId("dsd87dsa9d87s9d7"); and only for this document (e.g. _id : ObjectId("43jh4j343j4j") ) and no other.

arrayIds 并非文档唯一,这就是为什么我需要将其用于特定文档的原因.如果要为数组中存在的每个文档更新该值,可以使用$ positional operator,但这不是我想要的.

The arrayIds are not unique to the document that's why I need it to be for a specific document. I could use the $ positional operator if I wanted to update that value within the array for every document it exists in, but that's not what I want.

我正在尝试在的问题中实现这一目标但是命令行解决方案也可以.

I am trying to accomplish this in java but a command line solution would work as well.

推荐答案

您仍然可以使用$ positional运算符来完成此操作.但是您需要指定父文档的objectid以及_arrayid过滤器.下面的命令行查询工作正常

You could still use $ positional operator to accomplish this. But you need to specify the objectid of the parent doc along with the _arrayid filter. The below command line query works fine

db.so.update({_id:ObjectId("4e719eb07f1d878c5cf7333c"),
              "array._arrayId":ObjectId("dsd87dsa9d87s9d7")},
              {$set:{"array.$.someField":"updated"}})

这篇关于如何更新MongoDB中特定文档的数组内特定嵌入文档的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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