13.Query for Null or Missing Fields-官方文档摘录

时间:2023-03-09 16:18:16
13.Query for Null or Missing Fields-官方文档摘录

1 插入数据

db.inventory.insertMany([
{ _id: 1, item: null },
{ _id: 2 }
])

2 查询null值

db.inventory.find({itme:null})

13.Query for Null or Missing Fields-官方文档摘录

如果要精确查找到对应的null的字段,应该

db.inventory.find({item:{$type:10}})

13.Query for Null or Missing Fields-官方文档摘录

3 查询是否存在这个元素

db.inventory.find({item:{$exists:false}})

13.Query for Null or Missing Fields-官方文档摘录

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:

Copy
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:

Copy
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) :

Copy
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:

Copy
db.inventory.find( { item : { $exists: false } } )

The query returns only the document that does not contain the item field:

SEE ALSO

The reference documentation for the $type and $exists operators.