Home > OS >  mongodb: regex with multiple excluded phrases
mongodb: regex with multiple excluded phrases

Time:12-15

how do I regex search in mongodb with multiple excluded items?

find X and (not regex-y) and (not regex z) etc.

CodePudding user response:

it should look like this:

db.getCollection('mycollection').find({$and: [{"fieldname":"some-value-I-want"},{"fieldname":{$not: /some-regex-I-dont-want-1/}} , {"fieldname":{$not: /some-regex-I-dont-want-2/}}]})

CodePudding user response:

One way, using a single regex pattern:

db.getCollection('mycollection').find({fieldName: {$regex: "^(?!Y|Z$)X$"}})

The regex pattern says to match:

^             from the start of the field
    (?!Y|Z$)  do not see patterns Y or Z
    X         match pattern X
$             end of the field
  • Related