表示不等于 null 或空值的 MongoDB 查询是什么?
要设置不等于 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 }
广告