Check if a field contains a string in MongoDB?


You can use $regex operator to check if a field contains a string in MongoDB. The syntax is as follows −

db.yourCollectionName.findOne({"yourFieldName":{$regex:".*yourValue.*"}});

To understand the above concept, let us create a collection with the document. The query to create a collection with a document is as follows −

> db.checkFieldContainsStringDemo.insertOne({"Id":1,"Name":"John"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c77d762fc4e719b197a12ed")
}
> db.checkFieldContainsStringDemo.insertOne({"Id":2,"Name":"Johnson"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c77d76bfc4e719b197a12ee")
}
> db.checkFieldContainsStringDemo.insertOne({"Id":3,"Name":"Carol"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c77d774fc4e719b197a12ef")
}
> db.checkFieldContainsStringDemo.insertOne({"Id":4,"Name":"Mike"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c77d77cfc4e719b197a12f0")
}
> db.checkFieldContainsStringDemo.insertOne({"Id":5,"Name":"Sam"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c77d784fc4e719b197a12f1")
}
> db.checkFieldContainsStringDemo.insertOne({"Id":6,"Name":"Larry"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c77d78cfc4e719b197a12f2")
}

Display all documents from a collection with the help of find() method. The query is as follows −

> db.checkFieldContainsStringDemo.find();

The following is the output −

{ "_id" : ObjectId("5c77d762fc4e719b197a12ed"), "Id" : 1, "Name" : "John" }
{ "_id" : ObjectId("5c77d76bfc4e719b197a12ee"), "Id" : 2, "Name" : "Johnson" }
{ "_id" : ObjectId("5c77d774fc4e719b197a12ef"), "Id" : 3, "Name" : "Carol" }
{ "_id" : ObjectId("5c77d77cfc4e719b197a12f0"), "Id" : 4, "Name" : "Mike" }
{ "_id" : ObjectId("5c77d784fc4e719b197a12f1"), "Id" : 5, "Name" : "Sam" }
{ "_id" : ObjectId("5c77d78cfc4e719b197a12f2"), "Id" : 6, "Name" : "Larry" }

Here is the query to check the field contains a particular string in MongoDB. Here the string we are searching in a field is “Johnson” −

> db.checkFieldContainsStringDemo.findOne({"Name":{$regex:".*Johnson.*"}});

The following is the output −

{
   "_id" : ObjectId("5c77d76bfc4e719b197a12ee"),
   "Id" : 2,
   "Name" : "Johnson"
}

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements