My query is:
db.users.find({"username" : {$regex : ".*substring.*"}});
Instead of getting usernames that contain 'substring', I need usernames that do not contain it.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With