Vaibhav Magon
Vaibhav Magon

Reputation: 1503

How to convert string to boolean in MongoDB?

I am new to mongo so excuse me if it's a noobish question. I have wrongfully updated a specific flag in mongo with "true"/"false" (type strings). I want a query so that I could update my collection and change the type of the flag from string "true" to boolean true.

Example:

{flag: "true"} to { flag : true}

So I have 2 questions:

  1. Can I do that with a query?
  2. If I can, how?

Upvotes: 8

Views: 9560

Answers (4)

mickl
mickl

Reputation: 49955

Strings can be converted to boolean in MongoDB v4.0 using $toBool operator. In this case

db.col.aggregate([
    {
        $project: {
            _id: 0,
            flagBool: { $toBool: "$flag" }
        }
    }
])

Outputs:

{ "flagBool" : true }

Upvotes: 1

chridam
chridam

Reputation: 103375

For relatively small collections, perform an update if the type of field is string:

db.collection.find({ "flag": { $type : 2 } }).forEach(function (doc){   
    var isTrueSet = (doc.flag === "true");
    doc.flag = isTrueSet; // convert field to Boolean
    db.collection.save(doc);
});

For medium/large collections you can use the bulkWrite API as

var cursor = db.collection.find({ "flag": { "$exists": true, "$type": 2 } }),
    ops = [];

cursor.forEach(function(doc){ 
    var isTrueSet = (doc.flag === "true");
    ops.push({ 
        "updateOne": {
            "filter": { "_id": doc._id },
            "update": { "$set": { "flag": isTrueSet } }
         }
    });

    if (ops.length == 1000) {
        db.collection.bulkWrite(ops);
        ops = [];
    }
});         

if (ops.length > 0) { db.collection.bulkWrite(ops); }

Upvotes: 5

Salvador Dali
Salvador Dali

Reputation: 222601

Just call these two queries:

db.coll.update({
   flag: "true"
}, {
   $set: {flag: true}
}, { multi: true })

db.coll.update({
   flag: "false"
}, {
   $set: {flag: false}
}, { multi: true })

First one changes all "true" to true, second you will get it.

For a medium/big collection this will work significantly faster than already suggested foreach statement.

Upvotes: 5

max li
max li

Reputation: 2457

See MongoDB Manual - Modify Documents. Example:

db.collectionName.update({_id: "yourid"}, {$set: {flag : true}})

Upvotes: 1

Related Questions