簡體   English   中英

mongodb使用條件查找文檔並更新相應文檔中的另一個字段

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM