我有一个包含多个文档的集合,这些文档遵循以下结构:
{
"_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" } }
)
关于Mongodb:从数组中查找和更新对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29971788/