- 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
Is it possible to make a case-insensitive query in MongoDB?
Yes, you can use regexp to make a case-insensitive query in MongoDB. The syntax is as follows:
db.yourCollectionName.find({"yourFieldName":/^yourvalue$/i});
To understand the above syntax, let us create a collection with some documents. The query to create a collection with documents is as follows:
> db.caseInsensitiveDemo.insertOne({"Name":"John"}); { "acknowledged" : true, "insertedId" : ObjectId("5c6d7a67f2db199c1278e7ef") } > db.caseInsensitiveDemo.insertOne({"Name":"JOHN"}); { "acknowledged" : true, "insertedId" : ObjectId("5c6d7ad6f2db199c1278e7f0") }
Display all documents from a collection with the help of find(). The query is as follows:
> db.caseInsensitiveDemo.find();
The following is the output:
{ "_id" : ObjectId("5c6d7a67f2db199c1278e7ef"), "Name" : "John" } { "_id" : ObjectId("5c6d7ad6f2db199c1278e7f0"), "Name" : "JOHN" }
Here is the query to make case insensitive query:
> db.caseInsensitiveDemo.find({"Name":/^john$/i});
The following is the output:
{ "_id" : ObjectId("5c6d7a67f2db199c1278e7ef"), "Name" : "John" } { "_id" : ObjectId("5c6d7ad6f2db199c1278e7f0"), "Name" : "JOHN" }
Advertisements
To Continue Learning Please Login
Login with Google