Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB Regex with multiple options

Tags:

regex

mongodb

How do I search in mongo with regex that has multiple options?

as per mongo documentation I can do,

db.collection.find( { field: { $regex: 'acme.*corp', $options: 'i' } } )

How do I do this with multiple options, say, i and m?

like $options: 'im'?

or maybe $options: ['i', 'm']?

like image 273
xcorat Avatar asked Nov 20 '13 01:11

xcorat


1 Answers

The correct syntax is this (most probably based on my observation which are listed below):

$options: 'im'

List of regex options with descriptions

Data:

db.a.insert({"a" : "hello Sam" })
db.a.insert({"a" : "hello sam" })
db.a.insert({"a" : "hello\nSam" })
db.a.insert({"a" : "hello\nsam" })
db.a.insert({"a" : "hello pam" })
db.a.insert({"a" : "hello Pam" })
db.a.insert({"a" : "hello\nPam" })
db.a.insert({"a" : "hello\npam" })

Code:

 db.a.find({a : {$regex : 'o.+sam', $options : 'is'}})       // Sam, sam, \nSam, \nsam
 db.a.find({a : {$regex : 'o.+sam', $options : 'i'}})        // Sam, sam, 
 db.a.find({a : {$regex : 'o.+sam', $options : 's'}})        // sam, \nsam
 db.a.find({a : {$regex : 'o.+sam', $options : ['i']}})      // sam
 db.a.find({a : {$regex : 'o.+sam', $options : ['i', 's']}}) // sam
 db.a.find({a : {$regex : 'o.+sam', $options : ['s']}})      // sam
like image 160
Salvador Dali Avatar answered Oct 23 '22 19:10

Salvador Dali