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:
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With