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
Find a value in lowercase from a MongoDB collection with documents
To find a value in lowercase from a MongoDB collection, use the toLowerCase() method in JavaScript when constructing your query. This allows you to search for documents where a field matches a specific value in lowercase format.
Syntax
db.collection.find({"fieldName": "VALUE".toLowerCase()});
Sample Data
Let us create a collection with documents containing subject names in different cases ?
db.demo172.insertMany([
{"SubjectName": "MySQL"},
{"SubjectName": "mongodb"},
{"SubjectName": "MongoDB"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e3838ce9e4f06af551997e1"),
ObjectId("5e3838d69e4f06af551997e2"),
ObjectId("5e3838db9e4f06af551997e3")
]
}
Display all documents from the collection ?
db.demo172.find();
{ "_id": ObjectId("5e3838ce9e4f06af551997e1"), "SubjectName": "MySQL" }
{ "_id": ObjectId("5e3838d69e4f06af551997e2"), "SubjectName": "mongodb" }
{ "_id": ObjectId("5e3838db9e4f06af551997e3"), "SubjectName": "MongoDB" }
Example: Find Document with Lowercase Value
Find the document where SubjectName matches "mongodb" in lowercase ?
db.demo172.find({"SubjectName": "MONGODB".toLowerCase()});
{ "_id": ObjectId("5e3838d69e4f06af551997e2"), "SubjectName": "mongodb" }
Key Points
- The
toLowerCase()method converts the search string to lowercase before matching. - This approach only finds documents with exact lowercase matches, not case-insensitive searches.
- For true case-insensitive searches, use regular expressions with the
iflag instead.
Conclusion
Use JavaScript's toLowerCase() method within your MongoDB query to find documents with exact lowercase field values. This technique is useful when you need to match specific lowercase formatted data in your collection.
Advertisements
