How to use $regex in MongoDB?


Following is the syntax to use $regex in MongoDB −

db.yourCollectionName.find({yourFieldName: { $regex: yourValue}});

Let us first create a collection with documents −

> db.regularExpressionDemo.insertOne({"UserName":"John"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cdffc25bf3115999ed51210")
}
> db.regularExpressionDemo.insertOne({"UserName":"JOHN"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cdffc2ebf3115999ed51211")
}
> db.regularExpressionDemo.insertOne({"UserName":"john"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cdffc35bf3115999ed51212")
}
> db.regularExpressionDemo.insertOne({"UserName":"JoHn"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cdffc3ebf3115999ed51213")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.regularExpressionDemo.find();

This will produce the following output −

{ "_id" : ObjectId("5cdffc25bf3115999ed51210"), "UserName" : "John" }
{ "_id" : ObjectId("5cdffc2ebf3115999ed51211"), "UserName" : "JOHN" }
{ "_id" : ObjectId("5cdffc35bf3115999ed51212"), "UserName" : "john" }
{ "_id" : ObjectId("5cdffc3ebf3115999ed51213"), "UserName" : "JoHn" }

Following is the query to use $regex −

> db.regularExpressionDemo.find({'UserName': { $regex: 'JOHN'}});

This will produce the following output −

{ "_id" : ObjectId("5cdffc2ebf3115999ed51211"), "UserName" : "JOHN" }

Let us now match all the cases. Following is the query −

> db.regularExpressionDemo.find({'UserName': { $regex: 'JOHN', $options: 'i' }});

This will produce the following output −

{ "_id" : ObjectId("5cdffc25bf3115999ed51210"), "UserName" : "John" }
{ "_id" : ObjectId("5cdffc2ebf3115999ed51211"), "UserName" : "JOHN" }
{ "_id" : ObjectId("5cdffc35bf3115999ed51212"), "UserName" : "john" }
{ "_id" : ObjectId("5cdffc3ebf3115999ed51213"), "UserName" : "JoHn" }
raja
Published on 14-Jun-2019 15:03:17
Advertisements