1 插入数据
db.inventory.insertMany([ { _id: 1, item: null }, { _id: 2 } ])
2 查询null值
db.inventory.find({itme:null})
如果要精确查找到对应的null的字段,应该
db.inventory.find({item:{$type:10}})
3 查询是否存在这个元素
db.inventory.find({item:{$exists:false}})
Different query operators in MongoDB treat null
values differently.
This page provides examples of operations that query for null
values using the db.collection.find()
method in the mongo
shell. The examples on this page use the inventory
collection. To populate theinventory
collection, run the following:
db.inventory.insertMany([
{ _id: 1, item: null },
{ _id: 2 }
])
You can run the operation in the web shell below:
Equality Filter
The { item : null }
query matches documents that either contain the item
field whose value is null
orthat do not contain the item
field.
For example, the following query returns both documents:
db.inventory.find( { item: null } )
Type Check
The { item : { $type: 10 } }
query matches documents that contains the item
field whose value isnull
only; i.e. the value of the item
field is of BSON Type Null
(i.e. 10
) :
db.inventory.find( { item : { $type: 10 } } )
The query returns only the document where the item
field has a null
value.
Existence Check
The { item : { $exists: false } }
query matches documents that do not contain the item
field:
db.inventory.find( { item : { $exists: false } } )
The query returns only the document that does not contain the item
field: