I'm sure I'm missing something very basic in MongoDB queries, can't seem to get this simple condition.
Consider this collection
> db.tests.find() { "_id" : ObjectId("..."), "name" : "Test1" , "deleted" : true} { "_id" : ObjectId("..."), "name" : "Test2" , "deleted" : false} { "_id" : ObjectId("..."), "name" : "Test3" } I would simply like to query all the items that are "not deleted"
I know how to find the item that has a "deleted" flag set to true:
> db.tests.find({deleted:true}) { "_id" : ObjectId("..."), "name" : "Test1" , "deleted" : true} But how do I find all items that are NOT "deleted" (e.g. negate the above query, or in other words, any items that either doesn't have a "deleted" field, or have it with value false
What I tried by guessing (please don't laugh...)
> db.tests.find({$not : {deleted: true}}) (returns no results)
> db.tests.find({$not : {$eq:{deleted:true}}}) error: { "$err" : "invalid operator: $eq", "code" : 10068 }
> db.tests.find({deleted:{$not: true}}) error: { "$err" : "invalid use of $not", "code" : 13041 }
> db.tests.find({deleted:{$not: {$eq:true}}}) error: { "$err" : "invalid use of $not", "code" : 13034 }
What am I missing?
In MongoDB, we can check the existence of the field in the specified collection using the $exists operator. When the value of $exists operator is set to true, then this operator matches the document that contains the specified field(including the documents where the value of that field is null).
Boolean is a native field type in BSON (MongoDB's server-side storage format, aka "Binary JSON"). Booleans use less storage than an integer or string and avoid any unexpected side effects of comparison.
Definition. Evaluates a boolean and returns the opposite boolean value; i.e. when passed an expression that evaluates to true , $not returns false ; when passed an expression that evaluates to false , $not returns true . For more information on expressions, see Expressions.
db.tests.find({deleted: {$ne: true}}) Where $ne stands for "not equal". (Documentation on mongodb operators)
For the sake of completeness, another way to do this is with $in:
db.test.find({deleted: {$in: [null, false]}}) Including null in the array pulls in the docs where the deleted field is missing. This query can use an index on {deleted: 1} in the current 2.6.6 MongoDB release.
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