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

Jac*_*ild 3 mongodb nosql mongodb-query

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

{
    "_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"
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

我想查找并更新视频的缩略图,我只知道其中的 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);
        }
      }
    );
  });
Run Code Online (Sandbox Code Playgroud)

chr*_*dam 7

使用$ 位置运算符更新thumbnail嵌入文档中具有id2的字段的值:

db.collection.update(
   { "videos.id": 2 },
   { "$set": { "videos.$.thumbnail" : "newThumbnail.jpg" } }
)
Run Code Online (Sandbox Code Playgroud)