如何检查 MongoDB 集合中的空字段?
要在 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" : "" }
广告