更新数组中的数组中的项目 [英] Update an item in an array that is in an array

查看:51
本文介绍了更新数组中的数组中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在mongodb集合中有一个这样的文档:

I have a document in a mongodb collection like this :

{
    sessions : [
        {
            issues : [ 
                {
                    id : "6e184c73-2926-46e9-a6fd-357b55986a28",
                    text : "some text"
                },   
                {
                    id : "588f4547-3169-4c39-ab94-8c77a02a1774",
                    text : "other text"
                }
            ]
        } 
    ]
} 

我想在第一届会议上更新ID为 588f4547-3169-4c39-ab94-8c77a02a1774 的问题.

And I want to update the issue with the id 588f4547-3169-4c39-ab94-8c77a02a1774 in the first session.

问题是我只知道这是第一个会话和问题ID(不是问题的索引!)

The problem is that I only know that it's the first session and the issue id (NOT the index of the issue !)

所以我尝试这样的事情:

So I try something like this :

db.mycollection.update({ "sessions.0.issues.id" : "588f4547-3169-4c39-ab94-8c77a02a1774"}, 
                       { $set: { "sessions.0.issues.$.text" : "a new text" }})

但是我得到了以下结果:

But I got the following result :

WriteResult({
    "nMatched" : 0,
    "nUpserted" : 0,
    "nModified" : 0,
    "writeError" : {
        "code" : 16837,
        "errmsg" : "The positional operator did not find the match needed from the query. Unexpanded update: sessions.0.issues.$.text"
    }

我该怎么做?

感谢您的帮助.

推荐答案

您必须使用以下(显然等效的)查询:

You have to use this (apparently equivalent) query:

db.mycollection.update({"sessions.0.issues": {$elemMatch: {id: <yourValue>}}}, {$set: {"sessions.0.issues.$.text": "newText"}})

请注意,您的更新表达式正确.

Notice that your update expression was correct.

有关 $elemMatch 的更多信息.

More information about $elemMatch.

顺便说一句, MongoDB参考明确指出,运算符不适用于遍历嵌套数组的查询".

Btw, MongoDB reference explicits that $ operator does not work "with queries that traverse nested arrays".

重要:$elemMatch仅适用于版本4或更高版本.

Important: $elemMatch only works with version 4 or more.

这篇关于更新数组中的数组中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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