Jack Wild
Jack Wild

Reputation: 2122

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);
        }
      }
    );
  });

Upvotes: 6

Views: 6177

Answers (1)

chridam
chridam

Reputation: 103335

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

Upvotes: 12

Related Questions