How to check empty field in a MongoDB collection?

MongoDBDatabaseBig Data Analytics

To check empty field in a MongoDB collection, use $exists along with $eq operator. Let us create a collection with documents −

> 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")
}

Display all documents from a collection with the help of find() method −

> db.demo485.find();

This will produce the following output −

{ "_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" : "" }

Following is the query to check empty field −

> db.demo485.find({"LastName" : {"$exists" : true, "$eq" : ""}})

This will produce the following output −

{ "_id" : ObjectId("5e82e9f6b0f3fa88e22790a8"), "FirstName" : "Chris", "LastName" : "" }
{ "_id" : ObjectId("5e82ea0fb0f3fa88e22790ab"), "FirstName" : "Robert", "LastName" : "" }
raja
Published on 11-May-2020 13:28:13
Advertisements