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
Check for Existing Document in MongoDB?
In MongoDB, you can check if a document exists in a collection using the findOne() method. This method returns the first document that matches the query criteria, or null if no document is found.
Syntax
db.collectionName.findOne({fieldName: "value"});
Sample Data
Let us create a collection with sample documents ?
db.checkExistingDemo.insertMany([
{"StudentName": "John"},
{"StudentName": "Carol"},
{"StudentName": "Sam"},
{"StudentName": "Mike"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cbdf90dac184d684e3fa265"),
ObjectId("5cbdf912ac184d684e3fa266"),
ObjectId("5cbdf916ac184d684e3fa267"),
ObjectId("5cbdf91bac184d684e3fa268")
]
}
Display all documents from the collection ?
db.checkExistingDemo.find();
{ "_id": ObjectId("5cbdf90dac184d684e3fa265"), "StudentName": "John" }
{ "_id": ObjectId("5cbdf912ac184d684e3fa266"), "StudentName": "Carol" }
{ "_id": ObjectId("5cbdf916ac184d684e3fa267"), "StudentName": "Sam" }
{ "_id": ObjectId("5cbdf91bac184d684e3fa268"), "StudentName": "Mike" }
Example: Check for Existing Document
Check if a student named "Carol" exists in the collection ?
db.checkExistingDemo.findOne({StudentName: "Carol"});
{ "_id": ObjectId("5cbdf912ac184d684e3fa266"), "StudentName": "Carol" }
Check for a non-existing document ?
db.checkExistingDemo.findOne({StudentName: "David"});
null
Key Points
-
findOne()returns the first matching document or null if no match is found. - Use this method to quickly verify document existence before performing operations.
- The result can be used in conditional logic to handle existing vs. non-existing cases.
Conclusion
The findOne() method is the most efficient way to check document existence in MongoDB. It returns the matching document or null, making it perfect for conditional operations and data validation.
Advertisements
