regex (regular expression) in MongoDB

You are here : Home / MongoDB Tutorial


Contents of page >


1) First, create and insert in STUDENT collection - Before doing search using regex (regular expression) in document in collection in MongoDB  >
db.STUDENT.insert({
 _id: 1,
 X: "first name abc",
 PHONE: [ "12", "34" ]
})

db.STUDENT.insert({
 _id: 2,
 X: "first name lmn",
 PHONE: [ "56", "78" ]
})


2) Query : Search using regex (regular expression)  in MongoDB>
Search all the document value of whose field contains "abc" using regex (regular expression).
We will use $regex operator.
db.STUDENT.find({X:{$regex: "abc"}})
Output>
{ "_id" : 1, "X" : "first name abc", "PHONE" : [ "12", "34" ] }

3) Query : Search using regex (regular expression) in different manner than above in MongoDB>
Search all the document value of whose field contains "abc" using regex (regular expression).
Here we won't any operator we will simply use /abc/
db.STUDENT.find({X: /abc/})
Output>
{ "_id" : 1, "X" : "first name abc", "PHONE" : [ "12", "34" ] }


4) Query : Search using regex (regular expression)>
Search all the document value of whose field contains "ab" using regex (regular expression).
Here we won't any operator we will simply use /ab/
db.STUDENT.find({X: /ab/})
Output>
{ "_id" : 1, "X" : "first name abc", "PHONE" : [ "12", "34" ] }

5) Query : Search using regex (regular expression) in array-field in document in collection in MongoDB >
Search all the document value of whose array-field contains 5 using regex (regular expression).
Here we won't any operator we will simply use /5/
db.STUDENT.find({PHONE: /5/})
Output>
{ "_id" : 2, "X" : "first name lmn", "PHONE" : [ "56", "78" ] }


6) Summary -
So in this MongoDB tutorial we learned to Search using regex (regular expression) >


Search all the document value of whose field contains "abc" using regex (regular expression).
db.STUDENT.find({X:{$regex: "abc"}})


Search all the document value of whose field contains "abc"
db.STUDENT.find({X: /abc/})


Search all the document value of whose field contains "ab"
Here we won't any operator we will simply use /ab/
db.STUDENT.find({X: /ab/})


Search all the document value of whose array-field contains 5 using regex (regular expression).
db.STUDENT.find({PHONE: /5/})

Having any doubt? or you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter. You may join our fbGroup or linkedInGroup as well.


RELATED LINKS>

What is MongoDB - A quick introduction to database

Labels: MongoDB
eEdit
Must read for you :