我想根据特定条件选择所有子文档,然后更新相同的子磁盘:
示例:
我有以下2个文件
{
"_id" : 5,
"item" : "TBD",
"stock" : 0,
"info" : {
"publisher" : "1111",
"pages" : 430
},
"tags" : [
"technology",
"computer"
],
"ratings" : [
{
"by" : "ijk",
"rating" : 4
},
{
"by" : "lmn",
"rating" : 5
}
],
"reorder" : false
}
{
"_id" : 6,
"item" : "TBD",
"stock" : 0,
"info" : {
"publisher" : "1111",
"pages" : 430
},
"tags" : [
"technology",
"computer"
],
"ratings" : [
{
"by" : "ijk",
"rating" : 4
},
{
"by" : "lmna",
"rating" : 5
}
],
"reorder" : false
}
在这种情况下,我想选择评级为5的子文档,然后用等级9更新所有这些子文档。
我怎样才能做到这一点。
答案 0 :(得分:0)
<强>更新强>
使用updateMany和位置运算符$更新匹配的索引
db.collectionName.updateMany({'ratings.rating':5}, {$set: {'ratings.$.rating':9}})
正如Alex在评论中提到的,上面的查询只会更新数组中的第一个匹配元素。如果要更新所有匹配元素,则必须迭代并更新每条记录
db.rate.find({'ratings.rating':5}).forEach(function(doc){
var ratings = [];
doc.ratings.forEach(function(r){
if(r.rating == 5){
r.rating = 9;
}
ratings.push(r);
});
db.rate.findOneAndUpdate({_id: doc._id}, {$set: {ratings: ratings}});
})