Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Return True if a document exists in MongoDB?
To check if a document exists in MongoDB, use the find() method with count() or limit(1) to return a boolean result. The count() > 0 approach returns true if documents match the query criteria.
Syntax
db.collection.find(query).count() > 0
Create Sample Data
First, let's create a collection with sample documents ?
db.documentExistsOrNotDemo.insertMany([
{"UserId": 101, "UserName": "John"},
{"UserId": 102, "UserName": "Chris"},
{"UserId": 102, "UserName": "Robert"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c9932bd330fd0aa0d2fe4cf"),
ObjectId("5c9932c6330fd0aa0d2fe4d0"),
ObjectId("5c9932ce330fd0aa0d2fe4d1")
]
}
Display all documents to verify the data ?
db.documentExistsOrNotDemo.find().pretty();
{
"_id": ObjectId("5c9932bd330fd0aa0d2fe4cf"),
"UserId": 101,
"UserName": "John"
}
{
"_id": ObjectId("5c9932c6330fd0aa0d2fe4d0"),
"UserId": 102,
"UserName": "Chris"
}
{
"_id": ObjectId("5c9932ce330fd0aa0d2fe4d1"),
"UserId": 102,
"UserName": "Robert"
}
Case 1: Document Exists (Returns True)
Check if a document with UserId 101 exists ?
db.documentExistsOrNotDemo.find({"UserId": 101}).count() > 0;
true
Case 2: Document Does Not Exist (Returns False)
Check if a document with UserId 110 exists ?
db.documentExistsOrNotDemo.find({"UserId": 110}).count() > 0;
false
Alternative Method: Using limit(1)
For better performance with large collections, use limit(1) to stop after finding the first match ?
db.documentExistsOrNotDemo.find({"UserId": 101}).limit(1).count() > 0;
true
Conclusion
Use find(query).count() > 0 to check document existence in MongoDB. This returns true if matching documents exist, false otherwise. For large collections, combine with limit(1) for better performance.
Advertisements
