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
Retrieve data from a MongoDB collection?
To retrieve data from a MongoDB collection, use the find() method to return all matching documents or findOne() to return a single document. These are the primary query methods for data retrieval in MongoDB.
Syntax
// Return all documents db.collection.find(query, projection); // Return single document db.collection.findOne(query, projection);
Sample Data
Let us create a collection with student documents ?
db.demo463.insertMany([
{"StudentName": "Chris Brown", "StudentAge": 21, "StudentCountryName": "US"},
{"StudentName": "David Miller", "StudentAge": 23, "StudentCountryName": "UK"},
{"StudentName": "John Doe", "StudentAge": 22, "StudentCountryName": "AUS"},
{"StudentName": "John Smith", "StudentAge": 24, "StudentCountryName": "US"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e7f7ec8cb66ccba22cc9dcf"),
ObjectId("5e7f7ed5cb66ccba22cc9dd0"),
ObjectId("5e7f7ee1cb66ccba22cc9dd1"),
ObjectId("5e7f7eefcb66ccba22cc9dd2")
]
}
Method 1: Retrieve All Documents with find()
Display all documents from the collection ?
db.demo463.find();
{ "_id": ObjectId("5e7f7ec8cb66ccba22cc9dcf"), "StudentName": "Chris Brown", "StudentAge": 21, "StudentCountryName": "US" }
{ "_id": ObjectId("5e7f7ed5cb66ccba22cc9dd0"), "StudentName": "David Miller", "StudentAge": 23, "StudentCountryName": "UK" }
{ "_id": ObjectId("5e7f7ee1cb66ccba22cc9dd1"), "StudentName": "John Doe", "StudentAge": 22, "StudentCountryName": "AUS" }
{ "_id": ObjectId("5e7f7eefcb66ccba22cc9dd2"), "StudentName": "John Smith", "StudentAge": 24, "StudentCountryName": "US" }
Method 2: Retrieve Single Document with findOne()
Retrieve a specific student document ?
db.demo463.findOne({"StudentName": "John Doe"});
{
"_id": ObjectId("5e7f7ee1cb66ccba22cc9dd1"),
"StudentName": "John Doe",
"StudentAge": 22,
"StudentCountryName": "AUS"
}
Key Differences
-
find()returns a cursor to all matching documents -
findOne()returns only the first matching document as an object - Both methods accept query filters and projection parameters
Conclusion
Use find() to retrieve multiple documents and findOne() for single document retrieval. Both methods support query filters to match specific criteria and return data from MongoDB collections efficiently.
Advertisements
