2

i need to do regex bases search on a single field which has a condtion "ab not dc". below query results error. suggest a proper query to use

db.getCollection('collection').aggregate(
[
{$match:{search_description:{$regex: "ab", "$options": "i"}}}
,{$match:{search_description:{$not:{$regex: "dc", "$options": "i"}}}}
]
)

above query results "errmsg" : "bad query: BadValue $not cannot have a regex" error message

1 Answers1

3

Since MongoDB supports negative lookahead, you can use

db.getCollection('collection').aggregate(
    [
        {$match:{search_description:{$regex: "^(?!.*db).*ab.*$", "$options": "i"}}}
    ]
)    
Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142