6

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']?

1 Answer 1

10

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.