MongoDB(14)- 查询 null 字段或缺少某个字段的文档

插入测试数据

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

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

 

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

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

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

 

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

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

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

 

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

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

 

只查询包含 item 字段的文档

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

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

 

posted @ 2021-06-02 15:16  小菠萝测试笔记  阅读(946)  评论(0编辑  收藏  举报