19

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$)"}})
blueren
  • 2,730
  • 4
  • 30
  • 47
  • 5
    You can also just combine `$not` and `$regex`... `{$not: {$regex: "^(.*SystemDefaultTemplate$)"}}` – CherryDT Nov 26 '20 at 11:38

1 Answers1

24

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+."

JBone
  • 1,724
  • 3
  • 20
  • 32
  • UPDATE 2023: The $not operator can perform logical NOT operation on both: Regular expression objects (i.e. /pattern/) For example: db.inventory.find( { item: { $not: /^p.*/ } } ) $regex operator expressions For example: db.inventory.find( { item: { $not: { $regex: "^p.*" } } } ) db.inventory.find( { item: { $not: { $regex: /^p.*/ } } } ) – Oukaasha Habib Aug 03 '23 at 21:18