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); } )
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.
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.
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".$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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With