MongoDB query to display documents with a specific name irrespective of case


For this, use $regex in MongoDB. We will search for document field value with name “David”, irrespective of case. Let us create a collection with documents −

> db.demo700.insertOne( { details: [ { Name:"david" }]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea6e6b1551299a9f98c93ac")
}
> db.demo700.insertOne( { details: [ { Name:"Chris" }]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea6e6b9551299a9f98c93ad")
}
> db.demo700.insertOne( { details: [ { Name:"DAVID" }]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea6e6bf551299a9f98c93ae")
}
> db.demo700.insertOne( { details: [ { Name:"David" }]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea6e6c4551299a9f98c93af")
}

Display all documents from a collection with the help of find() method −

> db.demo700.find();

This will produce the following output −

{ "_id" : ObjectId("5ea6e6b1551299a9f98c93ac"), "details" : [ { "Name" : "david" } ] }
{ "_id" : ObjectId("5ea6e6b9551299a9f98c93ad"), "details" : [ { "Name" : "Chris" } ] }
{ "_id" : ObjectId("5ea6e6bf551299a9f98c93ae"), "details" : [ { "Name" : "DAVID" } ] }
{ "_id" : ObjectId("5ea6e6c4551299a9f98c93af"), "details" : [ { "Name" : "David" } ] }

Following is the query to display documents with a specific name irrespective of case −

> db.demo700.find({"details.Name":{$regex:/^David$/i}});

This will produce the following output −

{ "_id" : ObjectId("5ea6e6b1551299a9f98c93ac"), "details" : [ { "Name" : "david" } ] }
{ "_id" : ObjectId("5ea6e6bf551299a9f98c93ae"), "details" : [ { "Name" : "DAVID" } ] }
{ "_id" : ObjectId("5ea6e6c4551299a9f98c93af"), "details" : [ { "Name" : "David" } ] }

Updated on: 14-May-2020

93 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements