Mongodb:从数组中查找和更新对象 属性

Mongodb: Finding and updating object property from array

我有一个包含多个文档的集合,这些文档遵循以下结构:

{
    "_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"
        }
    ]
}

我想查找并更新一个视频的缩略图,我只知道视频的id,但不知道它在哪个文档中。

这是我目前尝试过的方法,但无法正常工作。我找到的所有示例都依赖于了解文档 ID 和要更新的对象的数组位置。我还发现做这样的查询发现文档没问题,但是将整个文档设置为新缩略图!

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

使用 $ positional operator 更新 id 为 2 的嵌入文档中 thumbnail 字段的值:

db.collection.update(
   { "videos.id": 2 },
   { "$set": { "videos.$.thumbnail" : "newThumbnail.jpg" } }
)