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?
franzlorenzon
  • 5,845
  • 6
  • 36
  • 58
Vaibhav Magon
  • 1,453
  • 1
  • 13
  • 29
  • possible duplicate of [MongoDB: How to change the type of a field?](http://stackoverflow.com/questions/4973095/mongodb-how-to-change-the-type-of-a-field) – Neo-coder Apr 16 '15 at 06:47

4 Answers4

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.

Salvador Dali
  • 214,103
  • 147
  • 703
  • 753
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); }
chridam
  • 100,957
  • 23
  • 236
  • 235
1

See MongoDB Manual - Modify Documents. Example:

db.collectionName.update({_id: "yourid"}, {$set: {flag : true}})
franzlorenzon
  • 5,845
  • 6
  • 36
  • 58
max li
  • 2,417
  • 4
  • 30
  • 44
0

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 }
mickl
  • 48,568
  • 9
  • 60
  • 89