要将查询设置为不等于null或空,请使用$nin运算符。语法如下
db.yourCollectionName.find({yourFieldName:{$nin:[null,""]}});
让我们创建包含文档的集合
> db.notEqualToNullOrEmptyDemo.insertOne({"UserName":"Larry","UserAge":24}); { "acknowledged" : true, "insertedId" : ObjectId("5c9d20b6a629b87623db1b26") } > db.notEqualToNullOrEmptyDemo.insertOne({"UserName":"","UserAge":29}); { "acknowledged" : true, "insertedId" : ObjectId("5c9d20bea629b87623db1b27") } > db.notEqualToNullOrEmptyDemo.insertOne({"UserName":"Sam","UserAge":32}); { "acknowledged" : true, "insertedId" : ObjectId("5c9d20c7a629b87623db1b28") } > db.notEqualToNullOrEmptyDemo.insertOne({"UserName":null,"UserAge":27}); { "acknowledged" : true, "insertedId" : ObjectId("5c9d20d2a629b87623db1b29") } > db.notEqualToNullOrEmptyDemo.insertOne({"UserName":"Robert","UserAge":26}); { "acknowledged" : true, "insertedId" : ObjectId("5c9d20dda629b87623db1b2a") } > db.notEqualToNullOrEmptyDemo.insertOne({"UserName":"","UserAge":23}); { "acknowledged" : true, "insertedId" : ObjectId("5c9d20e7a629b87623db1b2b") }
以下是在find()
方法的帮助下显示集合中所有文档的查询
> db.notEqualToNullOrEmptyDemo.find().pretty();
这将产生以下输出
{ "_id" : ObjectId("5c9d20b6a629b87623db1b26"), "UserName" : "Larry", "UserAge" : 24 } { "_id" : ObjectId("5c9d20bea629b87623db1b27"), "UserName" : "", "UserAge" : 29 } { "_id" : ObjectId("5c9d20c7a629b87623db1b28"), "UserName" : "Sam", "UserAge" : 32 } { "_id" : ObjectId("5c9d20d2a629b87623db1b29"), "UserName" : null, "UserAge" : 27 } { "_id" : ObjectId("5c9d20dda629b87623db1b2a"), "UserName" : "Robert", "UserAge" : 26 } { "_id" : ObjectId("5c9d20e7a629b87623db1b2b"), "UserName" : "", "UserAge" : 23 }
以下是将条件设置为不等于null或为空的查询
> db.notEqualToNullOrEmptyDemo.find({UserName:{$nin:[null,""]}}).pretty();
这将产生以下输出
{ "_id" : ObjectId("5c9d20b6a629b87623db1b26"), "UserName" : "Larry", "UserAge" : 24 } { "_id" : ObjectId("5c9d20c7a629b87623db1b28"), "UserName" : "Sam", "UserAge" : 32 } { "_id" : ObjectId("5c9d20dda629b87623db1b2a"), "UserName" : "Robert", "UserAge" : 26 }