How to properly use 'exist' function in MongoDB like in SQL?


To check for existence of a record, use findOne() in MongoDB. Let us first create a collection with documents −

> db.existsAlternateDemo.insertOne({"StudentName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e06d23f9e4dae213890ac5c")
}
> db.existsAlternateDemo.insertOne({"StudentName":"Chris","StudentAge":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e06d2559e4dae213890ac5d")
}
>db.existsAlternateDemo.insertOne({"StudentName":"Chris","StudentAge":22,"StudentCountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e06d2689e4dae213890ac5e")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.existsAlternateDemo.find();

This will produce the following output −

{ "_id" : ObjectId("5e06d23f9e4dae213890ac5c"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5e06d2559e4dae213890ac5d"), "StudentName" : "Chris", "StudentAge" : 21 }
{ "_id" : ObjectId("5e06d2689e4dae213890ac5e"), "StudentName" : "Chris", "StudentAge" : 22, "StudentCountryName" : "US" }

Here is the query to properly use 'exist' function in MongoDB like in SQL i.e. findOne() −

> db.existsAlternateDemo.findOne({"StudentCountryName" : "US"});

This will produce the following output −

{
   "_id" : ObjectId("5e06d2689e4dae213890ac5e"),
   "StudentName" : "Chris",
   "StudentAge" : 22,
   "StudentCountryName" : "US"
}

Updated on: 27-Mar-2020

93 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements