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


Let us first create a collection with documents wherein one of the fields is StudentName −

> db.lowerCaseDemo.insertOne({"StudentName":"JOHN SMith"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd9a86fb50a6c6dd317ad9f")
}
> db.lowerCaseDemo.insertOne({"StudentName":"CAROL TAYLor"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd9a88fb50a6c6dd317ada0")
}
> db.lowerCaseDemo.insertOne({"StudentName":"DAVID Miller"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd9a89fb50a6c6dd317ada1")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.lowerCaseDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cd9a86fb50a6c6dd317ad9f"),
   "StudentName" : "JOHN SMith"
}
{
   "_id" : ObjectId("5cd9a88fb50a6c6dd317ada0"),
   "StudentName" : "CAROL TAYLor"
}
{
   "_id" : ObjectId("5cd9a89fb50a6c6dd317ada1"),
   "StudentName" : "DAVID Miller"
}

Following is the query to implement toLowerCase() −

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

Let us check all the documents once again −

> db.lowerCaseDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cd9a86fb50a6c6dd317ad9f"),
   "StudentName" : "john smith"
}
{
   "_id" : ObjectId("5cd9a88fb50a6c6dd317ada0"),
   "StudentName" : "carol taylor"
}
{
   "_id" : ObjectId("5cd9a89fb50a6c6dd317ada1"),
   "StudentName" : "david miller"
}

Updated on: 30-Jul-2019

138 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements