Search a string with special characters in a MongoDB document?

MongoDBDatabaseBig Data Analytics

To search a string with special characters in MongoDB document, you can use \. Here, we have special character $ in our string.

Let us first implement the following query to create a collection with documents

>db.searchDocumentWithSpecialCharactersDemo.insertOne({"UserId":"Smith$John123","UserFirstName":"John","UserLastName":"Smith"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c987b98330fd0aa0d2fe4b1")
}
>db.searchDocumentWithSpecialCharactersDemo.insertOne({"UserId":"Taylor$Carol983","UserFirstName":"Carol","UserLastName":"Taylor"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c987bdb330fd0aa0d2fe4b2")
}
>db.searchDocumentWithSpecialCharactersDemo.insertOne({"UserId":"Doe$John999","UserFirstName":"John","UserLastName":"Doe"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c987bee330fd0aa0d2fe4b3")
}
>db.searchDocumentWithSpecialCharactersDemo.insertOne({"UserId":"Miller$David555","UserFirstName":"David","UserLastName":"Miller"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c987c01330fd0aa0d2fe4b4")
}

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

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

This will produce the following output

{
   "_id" : ObjectId("5c987b98330fd0aa0d2fe4b1"),
   "UserId" : "Smith$John123",
   "UserFirstName" : "John",
   "UserLastName" : "Smith"
}
{
   "_id" : ObjectId("5c987bdb330fd0aa0d2fe4b2"),
   "UserId" : "Taylor$Carol983",
   "UserFirstName" : "Carol",
   "UserLastName" : "Taylor"
}
{
   "_id" : ObjectId("5c987bee330fd0aa0d2fe4b3"),
   "UserId" : "Doe$John999",
   "UserFirstName" : "John",
   "UserLastName" : "Doe"
}
{
   "_id" : ObjectId("5c987c01330fd0aa0d2fe4b4"),
   "UserId" : "Miller$David555",
   "UserFirstName" : "David",
   "UserLastName" : "Miller"
}

Following is the query to search string with special characters in a MongoDB document. Here, we are searching for a string John with special character $

> db.searchDocumentWithSpecialCharactersDemo.find({ UserId : /.*\$John.*/i }).pretty();

This will produce the following output:

{
   "_id" : ObjectId("5c987b98330fd0aa0d2fe4b1"),
   "UserId" : "Smith$John123",
   "UserFirstName" : "John",
   "UserLastName" : "Smith"
}
{
   "_id" : ObjectId("5c987bee330fd0aa0d2fe4b3"),
   "UserId" : "Doe$John999",
   "UserFirstName" : "John",
   "UserLastName" : "Doe"
}
raja
Published on 11-Apr-2019 12:25:08
Advertisements