regexmongodbmongodb-queryregex-negation

Mongo regex for "not match" or inverse


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$)"}})

Solution

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

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

    ?! is a "negative lookahead". And here is some explanation about negative lookaheads:

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