![](/img/trans.png)
[英]MongoDB find matching document and update matching field inside array of objects
[英]mongodb find documents using condition and update another field in the respective document
我想在我的收藏夾中找到以下任何文檔:
然后將其業余愛好的值設置為與體育領域相等。
db.myCollection.update(
{ $or: [{"hobby": {$exists: false} },{"hobby": ""}]}
, {
$set: {
hobby: ????sports
}
}, {
multi: true
},
function(err, result) {
console.log(result);
console.log(err);
})
通過上面的命令,我想將體育運動的值作為固定值傳遞給所有匹配的文檔。 有什么方法可以獲取其相應的運動價值並將其設置為愛好 ?
您必須在2個查詢中執行此操作:
db.myCollection.find({
$or: [{ "hobby": { $exists: false } }, { "hobby": "" }]
}).toArray().forEach(function (item) {
db.myCollection.update(
{ _id: item._id },
{ $set: { hobby: item.sports } },
{ multi: true }
)
})
})
這是正確更新值的修改后的版本:
db.myCollection.find({
$or: [{ "hobby": { $exists: false } }, { "hobby": "" }]
}).toArray().forEach(function (item) {
db.myCollection.update(
{ _id: item._id },
{ $set: { hobby: item.sports } },
{ multi: true }
)
})
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.