Reputation: 16436
I was checking logic for querying on non-values and noticed when using the mongo
shell, it differentiates between undefined
and null
values.
> use test
> db.test.insert({ a : 1, b : null, c : undefined })
> db.test.insert({ a : null, b : undefined, c : 1 })
> db.test.insert({ a : undefined, b : 1, c : null })
When you query on the collection, you get this:
> db.test.find()
{ "_id" : ObjectId("52d95575c9333565e80ccb22"), "a" : 1, "b" : null, "c" : null }
{ "_id" : ObjectId("52d9557fc9333565e80ccb23"), "a" : null, "b" : null, "c" : 1 }
{ "_id" : ObjectId("52d95586c9333565e80ccb24"), "a" : null, "b" : 1, "c" : null }
When you query on null
however, it only retrieves records who was explicitly set to null
.
> db.test.find({ a : null })
{ "_id" : ObjectId("52d9557fc9333565e80ccb23"), "a" : null, "b" : null, "c" : 1 }
Is this a bug in MongoDB? How can I properly query for null/ undefined/ non-set fields?
So I can query for not-set values with this:
db.test.find({ $or : [ { a : null }, { a : { $exists : false } } ] })
But in this example though, it still only returns the single record:
{ "_id" : ObjectId("52d9557fc9333565e80ccb23"), "a" : null, "b" : null, "c" : 1 }
Anyone know why/ how MongoDB differentiates between undefined
and null
? Is this an issue with how the data was entered in MongoDB?
Upvotes: 10
Views: 17974
Reputation: 516
In case you wonder, why MongoDB casts undefined
to null
instead of just ignoring such properties - ignoreUndefined
flag could solve this behaviour.
https://mongodb.github.io/node-mongodb-native/2.1/reference/connecting/connection-settings/
Upvotes: 2
Reputation: 57192
If you want to return a document where a field exists AND is not null, use { a : {$ne : null}}
Undefined and null values are different, but the shell shows them both as null - https://jira.mongodb.org/browse/SERVER-6102
Upvotes: 10
Reputation: 77627
You should be using $exists to check for values that don't have the field.
Upvotes: 0