技术干货| MongoDB如何查询Null或不存在的字段?

755 阅读1分钟

在MongoDB中不同的查询操作符对于null值处理方式不同。

本文提供了使用mongo shell中的db.collection.find() 方法查询null值的操作案例。案例中使用的inventory集合数据可以通过下面的语句产生。

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

等值匹配

当使用**{item:null}作为查询条件的时候,返回的是item字段值为null的文档或者不包含item**字段的文档。

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

该查询返回inventory集合中的所有文档。

类型检查

当使用**{item:{$type:10}}**作为查询条件的时候,仅返回item字段值为null的文档。item字段的值是BSON TYPE NULL(type number 10)。

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

该查询仅返回item字段值为null的文档。

存在检查

当使用**{item:{$exists:false}}作为查询条件的时候,返回不包含item**字段的文档。

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

该查询仅返回不包含item字段的文档。

相关文档

$type

$exists

原文链接:

www.mongodb.com/docs/manual…

关于作者:张芷嘉

MongoDB中文用户文档·CRUD操作章节负责人

喜欢跑步,做饭,睡觉,出门三公里就困。使用MongoDB两年,倍感丝滑。