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 th
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):
"username"."username" by its lowercase version.Don't forget { multi: true }, otherwise only the first matching document will be updated.