j_walker_dev
j_walker_dev

Reputation: 1063

Using mongodb driver how to do not in $regex query

From searching the internet i am not sure if this is possible so i figured i would ask you smart people.

I am trying to allow a admin users of a site free range to do more advanced search queries. The db is mongo. Whatever is inputed into the search input gets put into a {"$regex": "{user input}"}.

I know i can use $not operator, but i am wondering if a NOT could be applied in the $regex field. This would save me from having to parse the input and fill in the $not and just let the $regex handle it.

This would only be available to admins who knew how to put the regex into the search input so i don't need to worry about complexity for simple users.

Thanks for any help.

EDIT: Also, i figured out later what i was really meaning with $not was $ne. Something where a user could type "someFieldName" $ne "someId" which would be put in the $regex query to mongo and get results for all documents where someFieldName doesn't have `someId'.

Upvotes: 1

Views: 1417

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

A regex has no $not-like operators.

If you want to return some line/entry that doesn't contain a query string, you can use

"^(?:(?!" + $query_string + ").)*$"

Here is a verbal description of ^(?:(?!query).)*$ regex that will match a line not containing the word "query":

enter image description here

To enforce PCRE flavor, you should use $regex operator with the pattern as a string (replace [your_query_string] with the actual query):

{ $regex: '^(?:(?![your_query_string]).)*$' }

Upvotes: 3

Related Questions