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

819 Views Asked by At

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

1

There are 1 best solutions below

0
On BEST ANSWER

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"}}}])
})