相关文章推荐
留胡子的黄豆  ·  30张图解: TCP ...·  1 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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": "burrisnewton@xoggle.com",

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"
                You can find the correct syntax from $cond document, correct this if: { $eq: ["$gender", "male"] }
– turivishal
                Sep 19, 2021 at 11:20
                verify again both are different this is incorrect > { if: { "gender":{ $eq: ["$gender", "male"]} and this is correct > if: { $eq: ["$gender", "male"] }
– turivishal
                Sep 19, 2021 at 11:28

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"

Mongo Playground

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

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.