Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query for boolean field as "not true" (e.g. either false or non existent)

Tags:

mongodb

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?

like image 409
Eran Medan Avatar asked Sep 16 '13 21:09

Eran Medan


People also ask

How do you check field is exist or not?

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).

What is Boolean MongoDB?

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.

What is$ not in aggregation?

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.


2 Answers

db.tests.find({deleted: {$ne: true}}) 

Where $ne stands for "not equal". (Documentation on mongodb operators)

like image 134
Sergio Tulentsev Avatar answered Sep 20 '22 22:09

Sergio Tulentsev


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.

like image 37
JohnnyHK Avatar answered Sep 20 '22 22:09

JohnnyHK