
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements