我有一个包含多个文档的集合,这些文档遵循以下结构:
{
"_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);
}
}
);
});
答案 0 :(得分:4)
使用 $ positional operator 更新thumbnail
为2的嵌入式文档中id
字段的值:
db.collection.update(
{ "videos.id": 2 },
{ "$set": { "videos.$.thumbnail" : "newThumbnail.jpg" } }
)