![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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" }
Advertisements