Dewfy
Dewfy

Reputation: 23614

MongoDB queries with null value

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

Upvotes: 17

Views: 32078

Answers (2)

Daniel K.
Daniel K.

Reputation: 5917

I had the same issue. After reading the following documents

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} };

Upvotes: 19

Andrew Orsich
Andrew Orsich

Reputation: 53675

Just checked following script at 2.0 and 2.0.2:

db.items.insert({ "_id" : 1001, "path" : [ ], "parent" : null })
db.items.insert({ "_id" : 1002, "path" : [ 1001 ], "parent" : NumberLong(1001) })
db.items.ensureIndex({"path":1});
db.items.ensureIndex({"parent":1},{sparse:false});
db.items.find({"parent":null})

actually returns one document that you expect:

{ "_id" : 1001,
  "path" : [],
  "parent" : null } 

Also you can look into this doc about querying and nulls, probably should help you avoid possible future mistakes.

Upvotes: 6

Related Questions