After a mongoimport from CSV I ended up with a large number of boolean fields stored as strings. The string values are all "TRUE", "FALSE" or empty.
How can I convert these fields to proper booleans, for the entire collection?
After a mongoimport from CSV I ended up with a large number of boolean fields stored as strings. The string values are all "TRUE", "FALSE" or empty.
How can I convert these fields to proper booleans, for the entire collection?
in mogodb shell you can use following statement
db.collection.find({"Fieldname":"TRUE"}).forEach(function(a){a.Fieldname=true; db.collection.save(a)})
db.collection.find({"Fieldname":"False"}).forEach(function(a){a.Fieldname=false; db.collection.save(a)})
this way you can change it from string to Boolean.
While you can do something very efficient with $set
possibly (although you're changing the nature of the size of data making string
s into boolean
s), I'd go simple in this case.
From the MongoDB console, you could use code like this:
db.myCollection.find().forEach(function(doc) {
var changed = false;
// loop through all fields, looking for "TRUE" or "FALSE"
for(var field in doc) {
var value = doc[field];
if (value === "TRUE") {
doc[field] = true;
changed = true;
} else if (value === "FALSE") {
doc[field] = false;
changed = true;
} else if (value === "" || value === null ) {
// remove empty
delete doc[field];
changed = true;
}
}
// continue pattern checking more fields if needed
if (changed) { // if something changed, update the entire document
db.myCollection.update({_id: doc._id}, doc);
}
});
Loop over the different fields that should be converted, and generate a query that contains the current key and the value that should be converted. For each document that matches the query, replace the string value with a boolean value.
var boolean_fields = ['Key_a1','Key_a2', ..,'Key_an'];
var queryFunction = function(key, value){
var expression = {};
expression[key] = value;
return expression;
}
boolean_fields.forEach(function(fieldname, index, array) {
db.products.find( queryFunction(fieldname, "TRUE") ).forEach( function (match) {
match[fieldname] = true; // convert field to boolean
db.products.save(match);
});
db.products.find( queryFunction(fieldname, "FALSE") ).forEach( function (match) {
match[fieldname] = false; // convert field to boolean
db.products.save(match);
});
db.products.find( queryFunction(fieldname, "") ).forEach( function (match) {
match[fieldname] = null; // remove string type
db.products.save(match);
});
});