Check that Field Exists with MongoDB?

MongoDBDatabaseBig Data Analytics

You can use the $exists and $ne operator for this. To understand the concept further, let us create a collection with document. The query to create a collection with document is as follows −

> db.checkFieldExistDemo.insertOne({"EmployeeId":1,"EmployeeName":"John","isMarried":true,"EmployeeSalary":4648585});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c76f7b31e9c5dd6f1f78281")
}
> db.checkFieldExistDemo.insertOne({"StudentId":2,"StudentName":"John","isMarried":false," StudentAge":19});
{
   "acknowledged" : true,0
   "insertedId" : ObjectId("5c76f7e11e9c5dd6f1f78282")
}

Display all documents from a collection with the help of find() method. The query is as follows −

> db.checkFieldExistDemo.find().pretty();

Output

{
   "_id" : ObjectId("5c76f7b31e9c5dd6f1f78281"),
   "EmployeeId" : 1,
   "EmployeeName" : "John",
   "isMarried" : true,
   "EmployeeSalary" : 4648585
}
{
   "_id" : ObjectId("5c76f7e11e9c5dd6f1f78282"),
   "StudentId" : 2,
   "StudentName" : "John",
   "isMarried" : false,
   "StudentAge" : 19
}

Here is the query to check whether the field exist in MongoDB.

Case 1 − When a field is present in more than one document. The query is as follows −

> db.checkFieldExistDemo.find({"isMarried":{$exists:true,$ne:null}}).pretty();

Output

{
   "_id" : ObjectId("5c76f7b31e9c5dd6f1f78281"),
   "EmployeeId" : 1,
   "EmployeeName" : "John",
   "isMarried" : true,
   "EmployeeSalary" : 4648585
}
{
   "_id" : ObjectId("5c76f7e11e9c5dd6f1f78282"),
   "StudentId" : 2,
   "StudentName" : "John",
   "isMarried" : false,
   "StudentAge" : 19
}

Case 2 − When a field is present in only one document. The query is as follows −

> db.checkFieldExistDemo.find({"StudentName":{$exists:true,$ne:null}}).pretty();

Output

{
   "_id" : ObjectId("5c76f7e11e9c5dd6f1f78282"),
   "StudentId" : 2,
   "StudentName" : "John",
   "isMarried" : false,
   "StudentAge" : 19
}
raja
Published on 28-Mar-2019 15:23:59
Advertisements