Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb: Finding and updating object property from array

I have a collection with multiple documents which follow this structure:

{
    "_id" : {
        "oid" : XXX
    },
    "name" : "Name",
    "videos" [
        {
          "id" : 1,
          "thumbnail" : "thumbnail.jpg",
          "name" : "Name here"
        },
        {
          "id" : 2,
          "thumbnail" : "thumbnail.jpg",
          "name" : "Name here"
        },
        {
          "id" : 3,
          "thumbnail" : "thumbnail.jpg",
          "name" : "Name here"
        }
    ]
}

I want to find and update the a thumbnail of a video, of which I only know the id, but not which document it is in.

This is what I've tried so far, but it's not working properly. All the examples I found relied on knowing the document id, and the array position of the object to update. I also found that doing a query like this found the document okay, but set the whole document as the new thumbnail!

db.collection(COLLECTION-NAME, function(err, collection){
    collection.update(
      { 'videos.id' : 2 },
      { $set: { thumbnail: "newThumbnail.jpg" } },
      function(err, result){
        if (!err){
          console.log('saved', result)
        } else {
          console.log('error', err);
        }
      }
    );
  });
like image 213
Jack Wild Avatar asked Apr 30 '15 15:04

Jack Wild


1 Answers

Use the $ positional operator to update the value of the thumbnail field within the embedded document having the id of 2:

db.collection.update(
   { "videos.id": 2 },
   { "$set": { "videos.$.thumbnail" : "newThumbnail.jpg" } }
)
like image 182
chridam Avatar answered Oct 24 '22 05:10

chridam