You can restrict case insensitive search in MongoDB with the help of '$regex'. The syntax is as follows −
db.yourCollectionName.find({"yourFieldName" : { '$regex':'^yourValue$'}});
You can use another regex. The syntax is as follows −
db.yourCollectionName.find({"Name" : { '$regex':/^yourValue$/i}});
To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.caseInsesitiveDemo.insertOne({"Name":"John"}); { "acknowledged" : true, "insertedId" : ObjectId("5c8bd66293c80e3f23815e83") } > db.caseInsesitiveDemo.insertOne({"Name":"Johnson"}); { "acknowledged" : true, "insertedId" : ObjectId("5c8bd66693c80e3f23815e84") } > db.caseInsesitiveDemo.insertOne({"Name":"Johny"}); { "acknowledged" : true, "insertedId" : ObjectId("5c8bd66a93c80e3f23815e85") }
Display all documents from a collection with the help of find() method. The query is as follows −
> db.caseInsesitiveDemo.find().pretty();
The following is the output −
{ "_id" : ObjectId("5c8bd66293c80e3f23815e83"), "Name" : "John" } { "_id" : ObjectId("5c8bd66693c80e3f23815e84"), "Name" : "Johnson" } { "_id" : ObjectId("5c8bd66a93c80e3f23815e85"), "Name" : "Johny" }
If you use below the type of regex then the list documents would be visible. The query is as follows −
> db.caseInsesitiveDemo.find({"Name" : { '$regex' : 'John' }});
The following is the output −
{ "_id" : ObjectId("5c8bd66293c80e3f23815e83"), "Name" : "John" } { "_id" : ObjectId("5c8bd66693c80e3f23815e84"), "Name" : "Johnson" } { "_id" : ObjectId("5c8bd66a93c80e3f23815e85"), "Name" : "Johny" }
Case 1 − If you want to restrict all those documents from displaying, use the first query −
> db.caseInsesitiveDemo.find({"Name" : { '$regex':'^John$'}});
The following is the output −
{ "_id" : ObjectId("5c8bd66293c80e3f23815e83"), "Name" : "John" }
Look at the above sample output, only ‘John’ is displaying..
Case 2 − If you want to restrict all those documents from displaying, use the second query.
The query is as follows −
> db.caseInsesitiveDemo.find({"Name" : { '$regex':/^John$/i}});
The following is the output −
{ "_id" : ObjectId("5c8bd66293c80e3f23815e83"), "Name" : "John" }