Aggregation change value of a boolean to string

Viewed 127

Have a collection with records , Need to convert boolean values of a column to string :

[
  {
    _id: "bmasndvhjbcw",
    name: "lucas",
    occupation: "scientist",
    passed_phd: true,
    age: 55,
    location: "texas",

  },
  {
    _id: "bmasndvhjbcx",
    name: "mark",
    occupation: "scientist",
    age: 45,
    passed_phd: true,
    location: "texas",

  },
  {
    _id: "bmasndvhjbca",
    name: "stuart",
    occupation: "lab assistant",
    age: 25,
    passed_phd: false,
    location: "texas",

  },
  {
    _id: "bmasndvhjbcq",
    name: "cooper",
    occupation: "physicist",
    age: 69,
    passed_phd: false,
    location: "texas"
  }
]

how to change boolean value of the records to string.

value that has true(boolean) in passed_phd should be converted to "yes"(string)

value that has false(boolean) in passed_phd should be converted to "no"(string)

[
  {
    _id: "bmasndvhjbcw",
    name: "lucas",
    occupation: "scientist",
    passed_phd: "yes",
    age: 55,
    location: "texas",

  },
  {
    _id: "bmasndvhjbcx",
    name: "mark",
    occupation: "scientist",
    age: 45,
    passed_phd: "yes",
    location: "texas",

  },
  {
    _id: "bmasndvhjbca",
    name: "stuart",
    occupation: "lab assistant",
    age: 25,
    passed_phd: "no",
    location: "texas",

  },
  {
    _id: "bmasndvhjbcq",
    name: "cooper",
    occupation: "physicist",
    age: 69,
    passed_phd: "no",
    location: "texas"
  }
]

mongodb version 4.0 .

1 Answers

The $cond aggregation pipeline operator can do this.

Beginning with MongoDB 4.2, these can be used in an update or in an aggregation pipeline, like:

db.collection.aggregate([
    {$set:{
            passed_phd:{
                        $cond:{
                               if:"$passed_phd",
                               then:"yes",
                               else:"no"
                              }
                        }
   }}
])
Related