Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get negation of a MongoDB query?

Tags:

mongodb

My query is:

db.users.find({"username" : {$regex : ".*substring.*"}});

Instead of getting usernames that contain 'substring', I need usernames that do not contain it.

like image 393
Ognjen Avatar asked Feb 06 '13 05:02

Ognjen


1 Answers

For this, you can use the $not operator:

db.test.find( { username: { $not: /substring/ } } );

Like in:

> db.test.insert( { username: "Derick Rethans" } );
> db.test.insert( { username: "Hannes Magunusson" } );
> db.test.find( { username: { $not: /ag/ } } );
{ "_id" : ObjectId("511258b36879ad400c26084f"), "username" : "Derick Rethans" }

However, you need to be aware that regular expressions and the use of the $not operator prevent indexes from being able to be used. If you need to do this query very often, you might want to have a good look at your schema design.

like image 59
Derick Avatar answered Sep 27 '22 22:09

Derick