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" }
Updated on: 2019-07-30T22:30:25+05:30

397 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements