Mongo regex for "not match" or inverse

blueren picture blueren · Dec 22, 2017 · Viewed 8.4k times · Source

My mongo documents all contain a field called templateName. There are a few documents that contain the value: a_SystemDefaultTemplate, b_SystemDefaultTemplate, c_SystemDefaultTemplate etc.

I would like to find those documents whose templateName does not end with (or contain) SystemDefaultTemplate

I know it can be done using the $not operator like so:

db.collection.find({templateName: {$not: /.*SystemDefaultTemplate$/}})

But how do I do the same using regex?

I have tried the below but it does not seem to work.

db.collection.find({templateName: {$regex: "^(.*SystemDefaultTemplate$)"}})

Answer

JBone picture JBone · Dec 22, 2017

try with negative look ahead ( meaning it should not contain the mentioned phrase)

db.collection.find({templateName: {$regex: "^(?!SystemDefaultTemplate$)"}})

?! is negative look ahead. And here is some explanation about it from http://rexegg.com/regex-disambiguation.html#lookarounds

"Negative Lookahead After the Match: \d+(?!\d| dollars) Sample Match: 100 in 100 pesos Explanation: \d+ matches 100, then the negative lookahead (?!\d| dollars) asserts that at that position in the string, what immediately follows is neither a digit nor the characters " dollars"

Negative Lookahead Before the Match: (?!\d+ dollars)\d+ Sample Match: 100 in 100 pesos Explanation: The negative lookahead (?!\d+ dollars) asserts that at the current position in the string, what follows is not digits then the characters " dollars". If the assertion succeeds, the engine matches the digits with \d+."