更新数组中的数组中的项

时间:2014-06-11 15:16:48

标签: mongodb

我在mongodb集合中有一个文档,如下所示:

{
    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 更新问题。

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

所以我尝试这样的事情:

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

但我得到了以下结果:

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"
    }

我该怎么做?

感谢您的帮助。

1 个答案:

答案 0 :(得分:10)

你必须使用这个(显然是等效的)查询:

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

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

有关$elemMatch的更多信息。

顺便说一下,MongoDB reference表明$运算符不适用于“遍历嵌套数组的查询”。

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

相关问题