[MongoDB]How do I query for fields that have null values?
{column:null}:结果为column的值为null或记录不包含column字段的数据;
{column:{$type:10}}:结果为记录包含column字段且值是null的数据;
{column:{$exists:false}}:结果为记录不包含column字段的数据;
Fields in a document may store null values, as in a notional collection, test, with the following documents:
{ _id: 1, cancelDate: null }
{ _id: 2 }
Different query operators treat null values differently:
-
The { cancelDate : null } query matches documents that either contains the cancelDate field whose value is null or that do not contain the cancelDate field:
db.test.find( { cancelDate: null } )
The query returns both documents:
{ "_id" : 1, "cancelDate" : null } { "_id" : 2 }
-
The { cancelDate : { $type: 10 } } query matches documents that contains the cancelDate field whose value is null only; i.e. the value of the cancelDate field is of BSON Type Null (i.e. 10) :
db.test.find( { cancelDate : { $type: 10 } } )
The query returns only the document that contains the null value:
{ "_id" : 1, "cancelDate" : null }
-
The { cancelDate : { $exists: false } } query matches documents that do not contain the cancelDate field:
db.test.find( { cancelDate : { $exists: false } } )
The query returns only the document that does not contain the cancelDate field:
{ "_id" : 2 }