Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating an array item using NodeJS, MongoDB & Monk

I have a data set like this:

{ 
  name : 'Doc Name',
  photos: [
      {
        name: 'photo1',
        url: 'http://.....'
      },
      {
        name: 'photo2',
        url: 'http://......'
      }
   ],
   etc ...

Using Monk https://github.com/LearnBoost/monk how do I update photo2? I can use an index as I am iterating over the fields at the moment.

My current attempt below gives me an error, and I can't use a variable for the JSON selector (as in the index).

collection.update({_id: data._id}, {photos[i].data: filename}, function(err, updatedata) {

            });
like image 654
Ryan Knell Avatar asked Feb 03 '14 01:02

Ryan Knell


People also ask

How do you update an array value in MongoDB using node JS?

To perform an update on all embedded array elements of each document that matches your query, use the filtered positional operator $[<identifier>] . The filtered positional operator $[<identifier>] specifies the matching array elements in the update document.

How do I update 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.


1 Answers

Updating items at a position in an array can be done using the positional $ operator

collection.update( 
    { _id: data.id, "photos.name": "photo2" }, 
    { $set: { "photos.$.data": "yourdata" } }
)
like image 54
Neil Lunn Avatar answered Oct 14 '22 17:10

Neil Lunn