Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB queries with null value

Tags:

null

mongodb

My collection (MongoDB v 2.0.2) has following records:

db.organization.find({})
{ "_id" : 1001, "path" : [ ], "parent" : null }
{ "_id" : 1002, "path" : [ 1001 ], "parent" : NumberLong(1001) }

organization has indexes:

db.organization.ensureIndex({"path":1});
db.organization.ensureIndex({"parent":1},{sparse:false});

(note I put awarnes sparse : false - to grant that null is indexed) But, executing:

db.organization.find({"parent":null})

Returns empty set. What is wrong? Thank you in advance

like image 576
Dewfy Avatar asked Feb 16 '12 13:02

Dewfy


People also ask

Is null query in MongoDB?

MongoDB fetch documents containing 'null' If we want to fetch documents from the collection "testtable" which contains the value of "interest" is null, the following mongodb command can be used : >db. testtable. find( { "interest" : null } ).

How do I ignore null values in MongoDB?

Solution 1: In case preservation of all null values[] or null fields in the array itself is not necessary. Filter out the not null elements using $filter , the ( all null elements) array would be empty, filter that out from documents using $match then $sort on values .

IS null operator in MongoDB?

The { item : null } query matches documents that either contain the item field whose value is null or that do not contain the item field. The query returns both documents in the collection.


1 Answers

I had the same issue. After reading the following documents

  • querying and nulls
  • BSON specification

I tried to query for the different BSON element types and found that my null was represented as a BSON element type 6 (undefined, deprecated) instead of the expected BSON element type 10 (null).

db.collection.find({ field: { "$type" : 6} };
like image 132
Daniel K. Avatar answered Oct 21 '22 09:10

Daniel K.