Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: How do I update a single subelement in an array, referenced by the index within the array?

Tags:

arrays

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.

Here's what I want to do in pseudo-json.

Before:

{   _id : ...,   other_stuff ... ,   my_array : [     { ... old content A ... },     { ... old content B ... },     { ... old content C ... }   ] } 

After:

{   _id : ...,   other_stuff ... ,   my_array : [     { ... old content A ... },     { ... NEW content B ... },     { ... old content C ... }   ] } 

Seems like the query should be something like this:

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

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.

like image 825
Abe Avatar asked Jul 07 '12 03:07

Abe


People also ask

How do you update a specific element in an array in MongoDB?

You can use the updateOne() or updateMany() methods to add, update, or remove array elements based on the specified criteria. It is recommended to use the updateMany() method to update multiple arrays in a collection.

How do I update a nested array in MongoDB?

Update Nested Arrays in Conjunction with $[]The $[<identifier>] filtered positional operator, in conjunction with the $[] all positional operator, can be used to update nested arrays. The following updates the values that are greater than or equal to 8 in the nested grades. questions array if the associated grades.

How do you update an object inside an object in MongoDB?

MongoDB syntax for updating an object inside an array within a document? For this, use findOneAndUpdate() in MongoDB. The findOneAndUpdate() method updates a single document based on the filter and sort criteria.


2 Answers

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}} ) 
like image 69
Abe Avatar answered Oct 18 '22 18:10

Abe


Update of an array element referenced by an index (e.g. 1 ) in Mongo Shell can also be done by directly indicating the index value:

db.my_collection.update(     {_id : "document_id"},     {$set : {"my_array.1.content" : "New content B"}} ) 
like image 35
tomaskazemekas Avatar answered Oct 18 '22 17:10

tomaskazemekas