scandll
scandll

Reputation: 11

How to replace a string in mongodb using $eq and $cond

I have a database containing people and their information (name, gender, etc...) Example:

{
    "id": 31,
    "balance": "$1,137.95",
    "age": 24,
    "eyeColor": "blue",
    "name": "Burris Newton",
    "gender": "male",
    "company": "XOGGLE",
    "email": "[email protected]",
}

I want to replace "male" by "H" and "female" by "F" for the gender in my database using $cond

I have written this but it doesn't work

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

Upvotes: 1

Views: 498

Answers (1)

Tom Slabbaert
Tom Slabbaert

Reputation: 22316

You want to be using piplined updates, this is available for Mongo version 4.2+, if you're using a lesser version you will have to do this in code by iterating each document one by one.

Here is the code sample using this feature:

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

Mongo Playground

*Note if documents can have missing gender field then you will have to address this otherwise they will get the "F" value.

Upvotes: 0

Related Questions