Check for existing documents/embedded documents in MongoDB


To check for existing documents/embedded documents, use $exists in MongoDB. Let us create a collection with documents −

> db.demo322.insertOne(
...  {'id':1001,
...    'details':[{'Score':10000,Name:"Bob"},
...       {'Score':98000,Name:"Sam"}
...    ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5113e2f8647eb59e56206c")
}
> db.demo322.insertOne(
... {'id':10002,
...    'details':[{'Score':9000},
...       {'Score':91000}
...       ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5113faf8647eb59e56206d")
}

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

> db.demo322.find();

This will produce the following output −

{
   "_id" : ObjectId("5e5113e2f8647eb59e56206c"), "id" : 1001, "details" : [
      { "Score" : 10000, "Name" : "Bob" }, { "Score" : 98000, "Name" : "Sam" }
   ]
}
{
   "_id" : ObjectId("5e5113faf8647eb59e56206d"), "id" : 10002, "details" : [
      { "Score" : 9000 }, { "Score" : 91000 }
   ] 
}

Following is the query to check for existing documents/embedded documents −

> db.demo322.find({"details.Name":{$exists:true}}).count() > 0;

This will produce the following output −

True

Updated on: 02-Apr-2020

162 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements