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

插入测试数据

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 操作符哦

 

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务