MongoDB query to search for string like “@email” in the field values


Search for email string using MongoDB find(). Let us create a collection with documents −

> db.demo727.insertOne({UserId:"John@email.com"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eab375f43417811278f5898")
}
> db.demo727.insertOne({UserId:"John@yahoo.com"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eab376043417811278f5899")
}
> db.demo727.insertOne({UserId:"Chris@EMAIL.com"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eab376143417811278f589a")
}

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

> db.demo727.find();

This will produce the following output −

{ "_id" : ObjectId("5eab375f43417811278f5898"), "UserId" : "John@email.com" }
{ "_id" : ObjectId("5eab376043417811278f5899"), "UserId" : "John@yahoo.com" }
{ "_id" : ObjectId("5eab376143417811278f589a"), "UserId" : "Chris@EMAIL.com" }

Following is the query to search for @email like string −

> db.demo727.find({"UserId":/@email/i});

This will produce the following output −

{ "_id" : ObjectId("5eab375f43417811278f5898"), "UserId" : "John@email.com" }
{ "_id" : ObjectId("5eab376143417811278f589a"), "UserId" : "Chris@EMAIL.com" }

Updated on: 15-May-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements