Mongo regex for "not match" or inverse [duplicate]
Asked Answered
P

1

23

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$)"}})
Pointblank answered 22/12, 2017 at 10:58 Comment(1)
You can also just combine $not and $regex... {$not: {$regex: "^(.*SystemDefaultTemplate$)"}}Pentup
M
26

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

Mathieu answered 22/12, 2017 at 13:20 Comment(2)
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.*/ } } } )Bulimia
It doesn't look to be working as expected: mongoplayground.net/p/sv9PyyZBT2l I guess you meant ^(?!.*SystemDefaultTemplate$) (including the .* inside)Ludwog

© 2022 - 2024 — McMap. All rights reserved.