Check that Field Exists with MongoDB?



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 }
Updated on: 2019-07-30T22:30:25+05:30

232 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements