How to get denial of MongoDB request?

My request:

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

Instead of getting usernames containing a "substring", I need usernames that don't contain it.

+5
source share
1 answer

For this you can use the $ not operator:

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

How 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 know that regular expressions and uses of the $ not operator do not allow indexes. If you need to make this request very often, you can take a good look at the design of the circuit.

+5
source

All Articles