
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MongoDB Query with Case Insensitive Search
For case, insensitive search, use regex in find() method. Following is the syntax −
db.demo572.find({"yourFieldName" : { '$regex':/^yourValue$/i}});
To understand the above syntax, let us create a collection with documents −
> db.demo572.insertOne({"CountryName":"US"});{ "acknowledged" : true, "insertedId" : ObjectId("5e915f0e581e9acd78b427f1") } > db.demo572.insertOne({"CountryName":"UK"});{ "acknowledged" : true, "insertedId" : ObjectId("5e915f17581e9acd78b427f2") } > db.demo572.insertOne({"CountryName":"Us"});{ "acknowledged" : true, "insertedId" : ObjectId("5e915f1b581e9acd78b427f3") } > db.demo572.insertOne({"CountryName":"AUS"});{ "acknowledged" : true, "insertedId" : ObjectId("5e915f20581e9acd78b427f4") } > db.demo572.insertOne({"CountryName":"us"});{ "acknowledged" : true, "insertedId" : ObjectId("5e915f25581e9acd78b427f5") }
Display all documents from a collection with the help of find() method −
> db.demo572.find();
This will produce the following output −
{ "_id" : ObjectId("5e915f0e581e9acd78b427f1"), "CountryName" : "US" } { "_id" : ObjectId("5e915f17581e9acd78b427f2"), "CountryName" : "UK" } { "_id" : ObjectId("5e915f1b581e9acd78b427f3"), "CountryName" : "Us" } { "_id" : ObjectId("5e915f20581e9acd78b427f4"), "CountryName" : "AUS" } { "_id" : ObjectId("5e915f25581e9acd78b427f5"), "CountryName" : "us" }
Following is the query for case insensitive search −
> db.demo572.find({"CountryName" : { '$regex':/^US$/i}});
This will produce the following output −
{ "_id" : ObjectId("5e915f0e581e9acd78b427f1"), "CountryName" : "US" } { "_id" : ObjectId("5e915f1b581e9acd78b427f3"), "CountryName" : "Us" } { "_id" : ObjectId("5e915f25581e9acd78b427f5"), "CountryName" : "us" }
Advertisements