Regex to ignore a specific character in MongoDB?


You can use regular expression along with $not operator to ignore a specific character and display rest of them. Let us first create a collection with documents −

> db.regexDemo.insertOne({"CustomerId":"Customer#1234","CustomerName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc7428f8f9e6ff3eb0ce436")
}
> db.regexDemo.insertOne({"CustomerId":"Customer5678","CustomerName":"Robert"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc7429e8f9e6ff3eb0ce437")
}
> db.regexDemo.insertOne({"CustomerId":"Customer#777","CustomerName":"Carol"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc742ae8f9e6ff3eb0ce438")
}
> db.regexDemo.insertOne({"CustomerId":"Customer777","CustomerName":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc742bc8f9e6ff3eb0ce439")
}

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

> db.regexDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cc7428f8f9e6ff3eb0ce436"),
   "CustomerId" : "Customer#1234",
   "CustomerName" : "Chris"
}
{
   "_id" : ObjectId("5cc7429e8f9e6ff3eb0ce437"),
   "CustomerId" : "Customer5678",
   "CustomerName" : "Robert"
}
{
   "_id" : ObjectId("5cc742ae8f9e6ff3eb0ce438"),
   "CustomerId" : "Customer#777",
   "CustomerName" : "Carol"
}
{
   "_id" : ObjectId("5cc742bc8f9e6ff3eb0ce439"),
   "CustomerId" : "Customer777",
   "CustomerName" : "David"
}

Case 1 − Here is the query to avoid using a specific character in MongoDB. The character is # −

> db.regexDemo.find({CustomerId: /^[^#]*$/}).pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cc7429e8f9e6ff3eb0ce437"),
   "CustomerId" : "Customer5678",
   "CustomerName" : "Robert"
}
{
   "_id" : ObjectId("5cc742bc8f9e6ff3eb0ce439"),
   "CustomerId" : "Customer777",
   "CustomerName" : "David"
}

Case 2 − Here is another query to avoid using a specific character in MongoDB. The character is # −

> db.regexDemo.find({CustomerId: {$not: /#/}}).pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cc7429e8f9e6ff3eb0ce437"),
   "CustomerId" : "Customer5678",
   "CustomerName" : "Robert"
}
{
   "_id" : ObjectId("5cc742bc8f9e6ff3eb0ce439"),
   "CustomerId" : "Customer777",
   "CustomerName" : "David"
}

Updated on: 30-Jul-2019

729 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements