Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update MongoDB collection using $toLower

Tags:

mongodb

I have an existing MongoDB collection containing user names. The user names contain both lower case and upper case letters.

I want to update all the user names so they only contain lower case letters.

I have tried this script, but it didn't work

db.myCollection.find().forEach(  function(e) {  e.UserName = $toLower(e.UserName);  db.myCollection.save(e);  } ) 
like image 737
sveatch42 Avatar asked Feb 24 '12 01:02

sveatch42


People also ask

How do you update a collection in MongoDB Java?

You can update a single document using the updateOne() method on a MongoCollection object. The method accepts a filter that matches the document you want to update and an update statement that instructs the driver how to change the matching document.


2 Answers

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.

like image 128
Gates VP Avatar answered Sep 20 '22 13:09

Gates VP


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.update(   {},   [{ $set: { username: { $toLower: "$username" } } }],   { multi: true } ) // { 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.
  • Don't forget { multi: true }, otherwise only the first matching document will be updated.

like image 25
Xavier Guihot Avatar answered Sep 20 '22 13:09

Xavier Guihot