Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 424
Vaibhav Magon Avatar asked Apr 16 '15 06:04

Vaibhav Magon


1 Answers

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); }
like image 156
chridam Avatar answered Sep 28 '22 06:09

chridam