MongoDb with Regular expression

Now we will discuss about regular expression matching with in queries in MongoDb using Python. The regular expression matching is obtained by $regex operator. First we inspect our data, click the button to view the mobile.json file.
Click to view JSON File
If you look at JSON file, you will see that, The JSON file contains the records of mobile and its accessories.
Now we discuss about how to use $regex for regular expression inside Pymongo. we stored the JSON document in mobile_collection of mobile database.
Before proceeding to code, let us understand syntax of $regex.
{ field : { $regex : pattern , $options : 'options'}}
field specify the field to be searched then we have a document which has $regex expression in it and pattern is the value of regular expression. The $options is used to enhance the search.
There are 4 type of option exists .
Letter Marks Range
iCase insensitivity to match upper and lower cases.
mFor patterns that include anchors (i.e. ^ for the start, $ for the end), match at the beginning or end of each line for strings with multiline values. Without this option, these anchors match at beginning or end of the string
xExtended capability to ignore all white space characters in the $regex pattern unless escaped or included in a character class.
s Allows the dot character (i.e. .) to match all characters including newline characters
Let us discuss the code.
MongoDB Document regular expression
MongoDB Document regular expression
Click to view Code

We are interested in the records which contain either iphone or android. Let us check the out-put.
MongoDB Document regular expression output
MongoDB Document regular expression
So, we are getting the out-put as per our code. In order to remove case sensitiveness use $options operator with option i. Replace 7th line with this line
query = {'record':{'$regex':'iphone|android','$options':'i'}} Save and run the code. Output would be like as shown below.
MongoDB Document regular expression output
MongoDB Document regular expression
You can see that a new records has been added.