Search a string with special characters in a MongoDB document?

To search a string with special characters in MongoDB document, you can use backslash (\) to escape the special character in a regular expression. Here, we have special character $ in our string.

Syntax

db.collection.find({ 
    "fieldName": /.*\specialCharacter.*/i 
});

Sample Data

Let us first create a collection with documents ?

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

Display all documents from the collection ?

db.searchDocumentWithSpecialCharactersDemo.find().pretty();
{
    "_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"
}

Example: Search String with Special Character

Search for string "John" with special character $ ?

db.searchDocumentWithSpecialCharactersDemo.find({ 
    UserId: /.*\$John.*/i 
}).pretty();
{
    "_id": ObjectId("5c987b98330fd0aa0d2fe4b1"),
    "UserId": "Smith$John123",
    "UserFirstName": "John",
    "UserLastName": "Smith"
}
{
    "_id": ObjectId("5c987bee330fd0aa0d2fe4b3"),
    "UserId": "Doe$John999",
    "UserFirstName": "John",
    "UserLastName": "Doe"
}

Key Points

  • Use backslash (\) before the special character to escape it
  • The i flag makes the search caseāˆ’insensitive
  • .* matches any characters before and after the target string

Conclusion

Use regular expressions with escaped special characters to search strings containing symbols like $, *, or + in MongoDB. The backslash escapes the special meaning of these characters.

Updated on: 2026-03-15T00:25:09+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements