🌟Regular Expression in MongoDB 🌟

Rahul Kumar
3 min readOct 1, 2022

--

Regular Expressions:

Matching patterns via regular expressions for string matching during querying.

Syntax:

The $options clause takes the following as parameters:

  • i → Performs a case insensitive match.
  • m → Performs pattern match that consists of anchors i.e. ^ for the beginning, $ for the end.
  • x → Ignores all white space characters in the pattern.
  • s → Allows dot character ( . ) to match all characters.

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

Example :

for regular expression we will use student database:

Inserting documents to student database in collections students_details:

> db.students_details.insertMany([
{ sno:111, sname:”AAA”, grade: “I”, marks: 93, remarks: “Very obedient and an ideal student” },
{ sno:222, sname:”BBB”, grade: “II”, marks: 90, remarks: “very obedient and punctual” },
{ sno:333, sname:”CCC”, grade: “IV”, marks: 76, remarks: “Needs improvement in communication skills” },
{ sno:444, sname:”DDD”, grade: “III”, marks: 88, remarks: “Should be punctual” }
])

Perform a LIKE match :

The following example matches all documents where the Sname field is like "DDD":

> db.students_details.find(
{ sname: { $regex: /DDD$/ } }
)

The following example matches all documents where the remarks field is like "very":

> db.students_details.find(
{ remarks: { $regex: /very/ } }
)

Perform Case-Insensitive Regular Expression Match:

By Using options ‘i’ to perform a case-insensitive match for documents with remarks value that starts with "very" :

> db.students_details.find(
{ remarks: { $regex: /^very/i } }
)
OR
> db.students_details.find(
{ remarks: { $regex: /^very/, $options: 'i' } }
)
OR
> db.students_details.find(
{ remarks: { $regex: '^very', $options: 'i' } }
)

match for documents with remarks value that ends with "punctual" :

> db.students_details.find(
{ remarks: { $regex: /punctual$/i } }
)

Multiline Match for Lines Starting with Specified Pattern:

lets insert some more documents in students :

> db.students_details.insertOne(
{ sno:555, sname:”EEE”, grade: “I”, marks: 87, remarks: “Very obedient.\nShould be punctual” }
)

The following example uses the m option to match lines starting with the letter S for multiline strings(in any line which starts with ‘S’):

> db.students_details.find({ remarks: { $regex: /^S/, $options: ‘m’ } } )

IF we remove options ‘m’ then it will give output one document.

Thank you….

--

--