MongoDB is not equal

I'm trying to display a query in MongoDB where the text field is not '' (space)

{ 'name' : { $not : '' }} 

However, I get an invalid use of $not error

I looked through the documentation, but the examples that they use are for complex cases (with regexp and $not negating another statement).

How do I do the simple thing I'm trying to do?

+77
mongodb
Mar 20 '12 at 16:29
source share
6 answers

$ne - $not should be followed by the standard operator:

Examples for $ne , which means not equal:

 use test switched to db test db.test.insert({author : 'me', post: ""}) db.test.insert({author : 'you', post: "how to query"}) db.test.find({'post': {$ne : ""}}) { "_id" : ObjectId("4f68b1a7768972d396fe2268"), "author" : "you", "post" : "how to query" } 

And now $not , which takes the predicate ( $ne ) and negates it ( $not ):

 db.test.find({'post': {$not: {$ne : ""}}}) { "_id" : ObjectId("4f68b19c768972d396fe2267"), "author" : "me", "post" : "" } 
+116
Mar 20 2018-12-12T00:
source share

If you want to make some $ne , then do

 db.users.find({name : {$nin : ["mary", "dick", "jane"]}}) 
+51
Jul 11 '13 at 13:32
source share

Use $ne instead of $not

http://docs.mongodb.org/manual/reference/operator/ne/#op._S_ne

 db.collections.find({"name": {$ne: ""}}); 
+29
Mar 20 2018-12-12T00:
source share

From Mongo docs :

The $not operator affects only other operators and cannot check fields and documents. So, use the $not operator for logical clauses and the $ne operator to check the contents of a field.

Since you are testing the field directly with $ne , this is the correct statement to use here.

Edit:

The situation in which you would like to use $not :

 db.inventory.find( { price: { $not: { $gt: 1.99 } } } ) 

This will select all documents where:

  • The value of the price field is less than or equal to 1.99 or the price
  • Field does not exist
+4
Feb 06 '16 at 3:15
source share

If the array has null and you want to avoid it:

 db.test.find({"contain" : {$ne :[] }}).pretty() 
0
May 2 '17 at 7:27
source share

Real life example; find all but the current user:

 var players = Players.find({ my_x: player.my_x, my_y: player.my_y, userId: {$ne: Meteor.userId()} }); 
-one
Sep 16 '14 at 3:11
source share



All Articles