Update MongoDB collection using $toLower

MongoDB does not have a concept of $toLower as a command. The solution is to run a big for loop over the data and issue the updates individually.

You can do this in any driver or from the shell:

db.myCollection.find().forEach(
  function(e) {
    e.UserName = e.UserName.toLowerCase();
    db.myCollection.save(e);
  }
)

You can also replace the save with an atomic update:

db.myCollection.update({_id: e._id}, {$set: {UserName: e.UserName.toLowerCase() } })

Again, you could also do this from any of the drivers, the code will be very similar.


EDIT: Remon brings up a good point. The $toLower command does exist as part of the aggregation framework, but this has nothing to do with updating. The documentation for updating is here.

Leave a Comment