6

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

1 Answer 1

12

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" } }
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.