MongoDB14- 查询 null 字段或缺少某个字段的文档

插入测试数据

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

后面的栗子都会用到这里的测试数据

 

查询匹配包含值为 null 的 item 字段或不包含 item 字段的文档

> db.inventory.find( { item: null } )
{ "_id" : 1,"item" :  }
{ "_id" : 2

如果我想单独的把字段值有 null 的文档找出来或者把没有 item 字段的文档找出来呢?

 

只查询包含值为 null 的 item 字段

> db.inventory.find( { item : { $type: 10 } } )
{ "_id" : null }

还记得吗,在 BSON 数据类型里面,null 的序号是 10

 

只查询不包含 item 字段的文档

> db.inventory.find({ item :{ $exists : false } })
{ "_id" : 2 }

 

只查询包含 item 字段的文档

 : true } })
{ "_id" : null }

记住如果想查询不包含/包含某个字段的文档,是用 $exists 操作符哦

 

相关文章

文章浏览阅读552次。com.mongodb.MongoQueryException: Quer...
文章浏览阅读635次,点赞9次,收藏8次。MongoDB 是一种 NoSQ...
文章浏览阅读2.1k次。和。_mongodb 日期类型
文章浏览阅读1.7k次。Scalestack等客户期待使用MongoDB Atla...
文章浏览阅读970次。SpringBoot整合中间件mongodb、ES_sprin...
文章浏览阅读673次。MongoDB 简介_尚医通sql