Refresh an item in an array that is in an array

I have a document in the mongodb collection, like this:

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

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

The problem is that I only know that this is the first session and the problem identifier (NOT the problem index!)

So, I am trying 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" } 

How can i do this?

Thanks for the help.

+7
mongodb
source share
1 answer

You should use this (apparently equivalent) query:

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

Please note that your update was correct.

Learn more about $elemMatch .

Btw, the MongoDB link explains that the $ operator does not work "with queries that cross nested arrays."

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

+9
source share

All Articles