MongoDB 虽然把开源协议变更了,闭源了。但是人们学习和使用 Mongo 的热情并没有减少和降低。今天我给大家分享一下,如何在 Mongo 中查询内容为空的字段或内容不为空的字段的结果集。
首先,我们查询出一个集合 xttblog 中 type 为空的记录。用法如下:
db.getCollection('xttblog').find({type:{$in:[null]}})
或者直接使用下面的查询也可以。
db.getCollection('xttblog').find({type:null]})
也可以在字段上加上 $exists:true
db.getCollection('xttblog').find({type:{$in:[null],$exists:true}})
查询 type 值不为空时(not null )也可以使用 $ne:null
db.getCollection("xttblog").find({type:{$ne:null}})
需要注意的是,$exists 无法利用到索引, 但 $NE 和 $in 可以用上索引, 所以处于性能的考虑尽可能用 $ne:null。当然前提是你的字段上有索引。
关于索引的查询优化,我们后面会专门的讲解 explain() 的用法。
: » MongoDB 中查询字段为空或非空的集合
原创文章,作者:3628473679,如若转载,请注明出处:https://blog.ytso.com/tech/aiops/252773.html