实施MongoDB $ exists和$ ne?
$exists用于检查文件是否存在,而$ne用于不相等条件。首先让我们创建一个包含文档的集合-
> db.existsDemo.insertOne({"Name":"Chris","Age":21}); { "acknowledged" : true, "insertedId" : ObjectId("5cd7c3916d78f205348bc650") } > db.existsDemo.insertOne({"Name":"","Age":null}); { "acknowledged" : true, "insertedId" : ObjectId("5cd7c39a6d78f205348bc651") } > db.existsDemo.insertOne({"Name":null,"Age":24}); { "acknowledged" : true, "insertedId" : ObjectId("5cd7c3a66d78f205348bc652") } > db.existsDemo.insertOne({"Age":23}); { "acknowledged" : true, "insertedId" : ObjectId("5cd7c3c36d78f205348bc653") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.existsDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd7c3916d78f205348bc650"), "Name" : "Chris", "Age" : 21 } { "_id" : ObjectId("5cd7c39a6d78f205348bc651"), "Name" : "", "Age" : null } { "_id" : ObjectId("5cd7c3a66d78f205348bc652"), "Name" : null, "Age" : 24 } { "_id" : ObjectId("5cd7c3c36d78f205348bc653"), "Age" : 23 }
以下是实现$exists运算符的查询-
> db.existsDemo.find({"$and":[ {"Name":{"$exists":true}}, {"Name":{"$ne": ""}}]});
这将产生以下输出-
{ "_id" : ObjectId("5cd7c3916d78f205348bc650"), "Name" : "Chris", "Age" : 21 } { "_id" : ObjectId("5cd7c3a66d78f205348bc652"), "Name" : null, "Age" : 24 }