Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use 'Not Like' operator in MongoDB

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

like image 475
KyungHoon Kim Avatar asked Nov 24 '13 13:11

KyungHoon Kim


People also ask

How do you use not equal to in MongoDB?

You can use the $ne operator (which stands for “not equal”) in MongoDB to query for documents where a field is not equal to a certain value. This particular example finds all documents in the collection titled myCollection where the team field is not equal to “Mavs.”

WHAT IS LIKE operator in MongoDB?

If we want SQL like “Like” operator in Mongo DB for string matching. But in mongo DB there is no such “like” operator instead it has regular expression to achieve a similar feature.

How do I exclude fields in MongoDB?

To exclude the _id field from the output documents of the $project stage, specify the exclusion of the _id field by setting it to 0 in the projection document.

How do I write a like statement in MongoDB?

In MongoDb, can use like using MongoDb reference operator regular expression(regex). For Same Ex.


1 Answers

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')} 
like image 127
shx2 Avatar answered Sep 28 '22 23:09

shx2