要检查MongoDB集合中的空字段,请使用$exists和$eq运算符。让我们创建一个包含文档的集合-
> db.demo485.insertOne({"FirstName":"Chris","LastName":""});{ "acknowledged" : true, "insertedId" : ObjectId("5e82e9f6b0f3fa88e22790a8") } > db.demo485.insertOne({"FirstName":"David","LastName":"Miller"});{ "acknowledged" : true, "insertedId" : ObjectId("5e82e9fdb0f3fa88e22790a9") } > db.demo485.insertOne({"FirstName":"Chris","LastName":"Brown"});{ "acknowledged" : true, "insertedId" : ObjectId("5e82ea03b0f3fa88e22790aa") } > db.demo485.insertOne({"FirstName":"Robert","LastName":""});{ "acknowledged" : true, "insertedId" : ObjectId("5e82ea0fb0f3fa88e22790ab") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo485.find();
这将产生以下输出-
{ "_id" : ObjectId("5e82e9f6b0f3fa88e22790a8"), "FirstName" : "Chris", "LastName" : "" } { "_id" : ObjectId("5e82e9fdb0f3fa88e22790a9"), "FirstName" : "David", "LastName" : "Miller" } { "_id" : ObjectId("5e82ea03b0f3fa88e22790aa"), "FirstName" : "Chris", "LastName" : "Brown" } { "_id" : ObjectId("5e82ea0fb0f3fa88e22790ab"), "FirstName" : "Robert", "LastName" : "" }
以下是检查空白字段的查询-
> db.demo485.find({"LastName" : {"$exists" : true, "$eq" : ""}})
这将产生以下输出-
{ "_id" : ObjectId("5e82e9f6b0f3fa88e22790a8"), "FirstName" : "Chris", "LastName" : "" } { "_id" : ObjectId("5e82ea0fb0f3fa88e22790ab"), "FirstName" : "Robert", "LastName" : "" }