【问题标题】:How to replace a string in mongodb using $eq and $cond如何使用 $eq 和 $cond 替换 mongodb 中的字符串
【发布时间】:2021-09-19 11:05:04
【问题描述】:

我有一个包含人员及其信息(姓名、性别等...)的数据库 示例:

{
    "id": 31,
    "balance": "$1,137.95",
    "age": 24,
    "eyeColor": "blue",
    "name": "Burris Newton",
    "gender": "male",
    "company": "XOGGLE",
    "email": "burrisnewton@xoggle.com",
}

我想使用 $cond 将数据库中的性别替换为“H”和“F”替换“男性”

我已经写了这个,但它不起作用

db.contacts.aggregate([
    {
        $project: {
            _id: 0,
            age: 1,
            name: 1,
            gender: {
                $cond: {
                    if: {
                        "gender": {$eq: ["$gender", "male"]},
                        then: "H",
                        else: "F"
                    }
                }
            }
        }
    }
])

【问题讨论】:

  • 你可以从$cond document找到正确的语法,更正这个if: { $eq: ["$gender", "male"] }
  • @turivishal 这就是使用的东西,这就是为什么我不明白为什么它不起作用
  • 再次验证两者是否不同 这是不正确的 > { if: { "gender":{ $eq: ["$gender", "male"]} 这是正确的 > if: { $eq: ["$gender", "male"] }

标签: mongodb


【解决方案1】:

您想使用piplined updates,这适用于 Mongo 4.2+ 版本,如果您使用的是较低版本,则必须在代码中逐个迭代每个文档。

以下是使用此功能的代码示例:

db.collection.updateMany(
{},
[
  {
    "$set": {
      "gender": {
        $cond: [
          {
            $eq: [
              "$gender",
              "male"
            ]
          },
          "H",
          "F"
        ]
      }
    }
  }
])

Mongo Playground

*请注意,如果文档可能缺少性别字段,那么您必须解决此问题,否则它们将获得 "F" 值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 2013-08-17
    相关资源
    最近更新 更多