Implement MongoDB toLowerCase() in a forEach loop to update the name of students?

To implement toLowerCase() in MongoDB using a forEach loop, you can iterate through documents and apply JavaScript's toLowerCase() method to convert field values to lowercase. This approach is useful for bulk string transformations.

Syntax

db.collection.find(query).forEach(
    function(document) {
        document.fieldName = document.fieldName.toLowerCase();
        db.collection.save(document);
    }
);

Create Sample Data

Let us create a collection with student documents containing mixed-case names ?

db.lowerCaseDemo.insertMany([
    {"StudentName": "JOHN SMith"},
    {"StudentName": "CAROL TAYLor"},
    {"StudentName": "DAVID Miller"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cd9a86fb50a6c6dd317ad9f"),
        ObjectId("5cd9a88fb50a6c6dd317ada0"),
        ObjectId("5cd9a89fb50a6c6dd317ada1")
    ]
}

Verify Initial Data

db.lowerCaseDemo.find().pretty();
{
    "_id": ObjectId("5cd9a86fb50a6c6dd317ad9f"),
    "StudentName": "JOHN SMith"
}
{
    "_id": ObjectId("5cd9a88fb50a6c6dd317ada0"),
    "StudentName": "CAROL TAYLor"
}
{
    "_id": ObjectId("5cd9a89fb50a6c6dd317ada1"),
    "StudentName": "DAVID Miller"
}

Apply toLowerCase() with forEach

db.lowerCaseDemo.find({StudentName: { $exists: true}}).forEach(
    function(v) {
        v.StudentName = v.StudentName.toLowerCase();
        db.lowerCaseDemo.save(v);
    }
);

Verify Updated Data

db.lowerCaseDemo.find().pretty();
{
    "_id": ObjectId("5cd9a86fb50a6c6dd317ad9f"),
    "StudentName": "john smith"
}
{
    "_id": ObjectId("5cd9a88fb50a6c6dd317ada0"),
    "StudentName": "carol taylor"
}
{
    "_id": ObjectId("5cd9a89fb50a6c6dd317ada1"),
    "StudentName": "david miller"
}

How It Works

  • find({StudentName: { $exists: true}}) selects documents with the StudentName field
  • forEach() iterates through each document
  • toLowerCase() converts the string to lowercase
  • save() updates the document in the collection

Conclusion

Using forEach with toLowerCase() provides an effective way to bulk-transform string fields in MongoDB. The combination of JavaScript methods within MongoDB's shell allows flexible document manipulation for data normalization tasks.

Updated on: 2026-03-15T01:22:34+05:30

216 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements