Search code examples
mongodbtypesmongo-shell

Mongo DB - Changing data type to Boolean resulting in object type


I am trying to update the data type of few fields from string to Boolean. I am using the following code in mongo shell :

db.SampleTest.find().forEach( function (d) {
d.smoke = new Boolean(d.smoke);
db.SampleTest.save(d);
});

But It updates the field as object type when viewed in mongodb compass. Please refer image

How to update the field type to Boolean?

Mongo Compass

enter image description here


Solution

  • If you use MongoDB 4.2, then below is the fix. You need to use $toBool and $set operators.

    db.SampleTest.find().forEach( function (d) {
        db.SampleTest.updateOne({"_id":d._id},[{"$set":{"smoke":{"$toBool": "$smoke"}}}])
    })