3

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

 2 years ago
source link: https://mongoing.com/archives/82043
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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

在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

原文链接:

https://www.mongodb.com/docs/manual/tutorial/query-for-null-fields/

关于作者:张芷嘉

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

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

社区招募

为了让社区组委会成员和志愿者朋友们灵活参与,同时我们为想要深度参与社区建设的伙伴们开设了“招募通道”,如果您想要在社区里面结交志同道合的技术伙伴,想要通过在社区沉淀有价值的干货内容,想要一个展示自己的舞台,提升自身的技术影响力,即刻加入社区贡献队伍~ 点击链接提交申请:http://mongoingmongoing.mikecrm.com/CPDCj1B


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK