Alternative syntax for operator $regex led to different search result

7 views
Skip to first unread message

olis...@gmail.com

unread,
Dec 15, 2017, 9:16:24 PM12/15/17
to mongodb-dev

To use $regex, we can use one of the following 3 syntaxes:
{ <field>: { $regex: /pattern/, $options: '<options>' } }
{ <field>: { $regex: 'pattern', $options: '<options>' } }
{ <field>: { $regex: /pattern/<options> } }

Now I have a test concern with the first 2 syntaxes:

#collection created for test
pradb>db.newtab.find()
{ "_id" : ObjectId("5a2a2555c8ba4994e594397f"), "f1" : "realapp" }
{ "_id" : ObjectId("5a2a255dc8ba4994e5943980"), "f1" : "racapp" }
{ "_id" : ObjectId("5a2a2562c8ba4994e5943981"), "f1" : "mysql" }
{ "_id" : ObjectId("5a2a2d60c8ba4994e5943982"), "f1" : "vcapp" }
{ "_id" : ObjectId("5a2a340fc8ba4994e5943983"), "f1" : "rea\napp" }
{ "_id" : ObjectId("5a2e4156c3b9a66ec4988f15"), "f1" : "suretrea" }

#if the pattern strings are quoted by '', then we can find out "realapp"
pradb>db.newtab.find({f1:{$regex:'rea \n# comment 1\nl',$options:"x"}})
{ "_id" : ObjectId("5a2a2555c8ba4994e594397f"), "f1" : "realapp" }

#But if we use // instead of '', "rea\napp" will be found out
pradb>db.newtab.find({f1:{$regex:/rea \n# comment 1\nl/,$options:"x"}})
{ "_id" : ObjectId("5a2a340fc8ba4994e5943983"), "f1" : "rea\napp" }

It seems that the // and '' result in different outputs.

Can anybody tell me how they works respectively ?

Reply all
Reply to author
Forward
0 new messages