How can I use 'Not Like' operator in MongoDB

KyungHoon Kim picture KyungHoon Kim · Nov 24, 2013 · Viewed 77.1k times · Source

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

Answer

shx2 picture shx2 · Nov 24, 2013

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')}