如何根据MongoDB集合中另一个字段的值更改字段的值?

cdmah0mi  于 2023-03-22  发布在  Go
关注(0)|答案(1)|浏览(179)

我的MongoDB中有这些文档

_id: ObjectId('64197b3c022b94220a7954e9'),
name: Frank,
gender: male,
_class: com.holdsport.model.person
_id: ObjectId('64197bd6018930affa3ff88f'),
name: Anna,
gender: female,
_class: com.holdsport.model.person
_id: ObjectId('64197be3a5c866cb5a93bf3e'),
name: Mary,
gender: female,
_class: com.holdsport.model.person

我想使用一个脚本,该脚本基本上遍历数据库中的所有文档,并根据性别更改_class。如果是男性,则应将其更改为com.holdsport.model.male,如果是女性,则应将其更改为com.holdsport.model.female

8yparm6h

8yparm6h1#

一种选择是:

db.collection.updateMany({
  gender: {
    $in: [
      "male",
      "female"
    ]
  }
},
[
  {
    $set: {
      _class: {
        $cond: [
          {
            $eq: [
              "$gender",
              "male"
            ]
          },
          "com.holdsport.model.male",
          "com.holdsport.model.female"
        ]
      }
    }
  }
])

了解它在playground example上的工作原理

相关问题