Update MongoDB collection using $toLower

Starting Mongo 4.2, db.collection.update() can accept an aggregation pipeline, finally allowing the update of a field based on its own value:

// { username: "Hello World" }
db.collection.updateMany(
  {},
  [{ $set: { username: { $toLower: "$username" } } }]
)
// { username: "hello world" }
  • The first part {} is the match query, filtering which documents to update (in this case all documents).

  • The second part [{ $set: { username: { $toLower: "$username" } } }], is the update aggregation pipeline (note the squared brackets signifying the use of an aggregation pipeline):

    • $set is a new aggregation operator which in this case modifies the value for "username".
    • Using $toLower, we modify the value of "username" by its lowercase version.

Very similar solution but this worked me in new mongo 3.2 Execute the following in Mongo Shell or equivalent DB tools like MongoChef!

db.tag.find({hashtag :{ $exists:true}}).forEach(
 function(e) {
   e.hashtag = e.hashtag.toLowerCase();
   db.tag.save(e);
});

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.

Tags:

Mongodb