How to update MongoDB collection using $toLower?


There is a $toLower operator in MongoDB to be used as part of aggregate framework. But, we can also use the for loop to iterate over the specific field and update one by one.

Let us first create a collection with documents

> db.toLowerDemo.insertOne({"StudentId":101,"StudentName":"John"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9b1b4515e86fd1496b38bf")
}
> db.toLowerDemo.insertOne({"StudentId":102,"StudentName":"Larry"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9b1b4b15e86fd1496b38c0")
}
> db.toLowerDemo.insertOne({"StudentId":103,"StudentName":"CHris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9b1b5115e86fd1496b38c1")
}
> db.toLowerDemo.insertOne({"StudentId":104,"StudentName":"ROBERT"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9b1b5a15e86fd1496b38c2")
}

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

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

This will produce the following output

{
   "_id" : ObjectId("5c9b1b4515e86fd1496b38bf"),
   "StudentId" : 101,
   "StudentName" : "John"
}
{
   "_id" : ObjectId("5c9b1b4b15e86fd1496b38c0"),
   "StudentId" : 102,
   "StudentName" : "Larry"
}
{
   "_id" : ObjectId("5c9b1b5115e86fd1496b38c1"),
   "StudentId" : 103,
   "StudentName" : "CHris"
}
{
   "_id" : ObjectId("5c9b1b5a15e86fd1496b38c2"),
   "StudentId" : 104,
   "StudentName" : "ROBERT"
}

Following is the query to update MongoDB like $toLower

> db.toLowerDemo.find().forEach(
...    function(lower) {
...       lower.StudentName = lower.StudentName.toLowerCase();
...       db.toLowerDemo.save(lower);
...    }
... );

Let us check the document once again from the above collection. Following is the query

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

This will produce the following output

{
   "_id" : ObjectId("5c9b1b4515e86fd1496b38bf"),
   "StudentId" : 101,
   "StudentName" : "john"
}
{
   "_id" : ObjectId("5c9b1b4b15e86fd1496b38c0"),
   "StudentId" : 102,
   "StudentName" : "larry"
}
{
   "_id" : ObjectId("5c9b1b5115e86fd1496b38c1"),
   "StudentId" : 103,
   "StudentName" : "chris"
}
{
   "_id" : ObjectId("5c9b1b5a15e86fd1496b38c2"),
   "StudentId" : 104,
   "StudentName" : "robert"
}

Updated on: 30-Jul-2019

524 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements