8

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?
1

4 Answers 4

5

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); }
Sign up to request clarification or add additional context in comments.

Comments

5

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.

Comments

1

See MongoDB Manual - Modify Documents. Example:

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

Comments

1

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 }

1 Comment

Please note that an empty string will be casted to true, unlike in many other languages. It's also possible to get a non-boolean value as null will cast to null.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.