121

I can use the SQL Like Operator using pymongo,

db.test.find({'c':{'$regex':'ttt'}})

But how can I use Not Like Operator?

I tried

db.test.find({'c':{'$not':{'$regex':'ttt'}})

but got error:

OperationFailure: $not cannot have a regex

themefield
  • 3,847
  • 30
  • 32
KyungHoon Kim
  • 2,859
  • 2
  • 23
  • 26

2 Answers2

187

From the docs:

The $not operator does not support operations with the $regex operator. Instead use // or in your driver interfaces, use your language’s regular expression capability to create regular expression objects. Consider the following example which uses the pattern match expression //:

db.inventory.find( { item: { $not: /^p.*/ } } )

EDIT (@idbentley):

{$regex: 'ttt'} is generally equivalent to /ttt/ in mongodb, so your query would become:

db.test.find({c: {$not: /ttt/}}

EDIT2 (@KyungHoon Kim):

In python, below one works:

'c':{'$not':re.compile('ttt')}
whoami - fakeFaceTrueSoul
  • 17,086
  • 6
  • 32
  • 46
shx2
  • 61,779
  • 13
  • 130
  • 153
78

You can do with regex which does not contain a word. Also, you can use $options => i for case of insensitive search.

Doesn't Contain string

db.collection.find({name:{'$regex' : '^((?!string).)*$', '$options' : 'i'}})

Exact case insensitive string

db.collection.find({name:{'$regex' : '^string$', '$options' : 'i'}})

Starts with string

db.collection.find({name:{'$regex' : '^string', '$options' : 'i'}})

Ends with string

db.collection.find({name:{'$regex' : 'string$', '$options' : 'i'}})

Contains string

db.collection.find({name:{'$regex' : 'string', '$options' : 'i'}})

Keep this as a bookmark, and a reference for any other alterations you may need. http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/

Pawel Gumiela
  • 1,992
  • 2
  • 20
  • 36
Somnath Muluk
  • 55,015
  • 38
  • 216
  • 226