Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to update MongoDB collection using $toLower?
To update a MongoDB collection using $toLower functionality, use the forEach() method to iterate through documents and apply JavaScript's toLowerCase() function. While $toLower is primarily an aggregation operator, this approach allows you to permanently update field values in your collection.
Syntax
db.collection.find().forEach(
function(document) {
document.fieldName = document.fieldName.toLowerCase();
db.collection.save(document);
}
);
Sample Data
First, let's create a collection with mixed-case student names ?
db.toLowerDemo.insertMany([
{"StudentId": 101, "StudentName": "John"},
{"StudentId": 102, "StudentName": "Larry"},
{"StudentId": 103, "StudentName": "CHris"},
{"StudentId": 104, "StudentName": "ROBERT"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c9b1b4515e86fd1496b38bf"),
ObjectId("5c9b1b4b15e86fd1496b38c0"),
ObjectId("5c9b1b5115e86fd1496b38c1"),
ObjectId("5c9b1b5a15e86fd1496b38c2")
]
}
Display Original Data
db.toLowerDemo.find().pretty();
{
"_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"
}
Update Using forEach() Method
Apply lowercase transformation to all StudentName fields ?
db.toLowerDemo.find().forEach(
function(lower) {
lower.StudentName = lower.StudentName.toLowerCase();
db.toLowerDemo.save(lower);
}
);
Verify Results
db.toLowerDemo.find().pretty();
{
"_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"
}
Key Points
- The
forEach()method iterates through each document in the collection - JavaScript's
toLowerCase()function converts strings to lowercase - The
save()method updates the document with the modified field value - This approach permanently modifies the actual collection data
Conclusion
While $toLower is an aggregation operator, you can achieve similar results for permanent updates using forEach() with JavaScript's toLowerCase(). This method iterates through documents and saves the modified values back to the collection.
Advertisements
