首页 > 解决方案 > 在 MongoDB 中,如何根据另一个字段有条件地更新具有不同值的文档

问题描述

我必须阅读多个文件。循环它们;如果文档有图像,我将状态设为“X”,如果没有,我将其设为“Y”。我已经这样实现了

const studies = await StudyModel.find({ status: 'uploading' });
studies.forEach(s => {
  // Some more synchronous operations
  const status = s.images ? 'X' : 'Y';
  // non blocking update study call
  StudyModel.Update({_id: study._id}, { status: studyStatus });
})

现在,如果在阅读研究之后和更新之前,用户在研究中添加图像会怎样。然后在 db 中有研究中的图像,状态应该是“X”,但代码会将其设为“Y”,因为它看不到新图像。这是一个罕见的情况,但已经发生了几次。

我正在寻找的是一种有条件地检查数据库中的图像并基于此进行更新的方法。这种东西。

StudyModel.Update({_id: id}, {$set: {status: {"$cond": {if: '$images', then: 'X', else: 'Y' } } } } )

有没有办法做到这一点?以及如何解决这样的问题?

标签: node.jsmongodbmongoosemongodb-query

解决方案


您可以使用 $exist 但有两个命令。

    // image is exist
    db.collection.updateMany(
      { status: 'uploading', image: { $exists: true } },
      { $set: { images: X} },
      {
        upsert: true,
      }
    )

  // image is not exist  
    db.collection.updateMany(
      { status: 'uploading', image: { $exists: false } },
      { $set: { images: Y} },
      {
        upsert: true,
      }
    )

推荐阅读