Return True if a document exists in MongoDB?


Let us first create a collection. Following is the query to create a collection with documents

> db.documentExistsOrNotDemo.insertOne({"UserId":101,"UserName":"John"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9932bd330fd0aa0d2fe4cf")
}
> db.documentExistsOrNotDemo.insertOne({"UserId":102,"UserName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9932c6330fd0aa0d2fe4d0")
}
> db.documentExistsOrNotDemo.insertOne({"UserId":102,"UserName":"Robert"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9932ce330fd0aa0d2fe4d1")
}

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

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

This will produce the following output

{
   "_id" : ObjectId("5c9932bd330fd0aa0d2fe4cf"),
   "UserId" : 101,
   "UserName" : "John"
}
{
   "_id" : ObjectId("5c9932c6330fd0aa0d2fe4d0"),
   "UserId" : 102,
   "UserName" : "Chris"
}
{
   "_id" : ObjectId("5c9932ce330fd0aa0d2fe4d1"),
   "UserId" : 102,
   "UserName" : "Robert"
}

Case 1: Following is the query that returns true if a document exists

> db.documentExistsOrNotDemo.find({"UserId":101}).count() > 0;

This will produce the following output

True

Case 2 Following is the query that returns false if a document does not exist

> db.documentExistsOrNotDemo.find({"UserId":110}).count() > 0;

This will produce the following output

False

Updated on: 30-Jul-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements