3

I'm trying to change field type to bool among all documents in collection. Here is the code

db.product.find().forEach(function(doc) {
if (doc.checked === "Y") {
doc.checked = true;
} else if (doc.checked === "N") {
doc.checked = false;
}
db.product.save(doc);
});

Mongodb returns no error but doesn't convert fields.

  • Can you paste the console output of db.product.findOne()? – harshavmb Dec 25 '15 at 7:18
  • { "_id" : ObjectId("56671a312253ec2b40921d2d"), "date" : ISODate("2015-12-08T17:58:09.000Z"), "checked" : "Y", "ports" : "38577,8081,6706" } – user1700494 Dec 25 '15 at 12:57
  • Your script logic is fine, i tested and it works. Are you running the script on the correct database? Is the collection sharded? – Antonios Dec 25 '15 at 22:13
  • Yes.. Your logic is correct and it worked fine for me.. – harshavmb Dec 26 '15 at 7:57
  • you can use bulk update as well. You can try the below query. var bulk = db.product.initializeUnorderedBulkOp(); bulk.find({checked:'Y'}).update({$set:{checked:true}}); bulk.find({checked:'N'}).update({$set:{checked:false}}); bulk.execute(); – harshavmb Dec 26 '15 at 8:02
0

I solved problem using 'db.product.update' instead of 'db.product.save'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.