Problem Statement
What is the difference between find() and findOne() methods in MongoDB?
Explanation
The find method returns a cursor pointing to all documents that match the query criteria. You can iterate through this cursor to access multiple documents. If no criteria is provided, find returns all documents in the collection.
The findOne method returns only the first document that matches the query criteria, or null if no match is found.
Use find when you expect multiple results and need to process them, and use findOne when you only need a single document, such as looking up a user by their unique identifier. findOne is more efficient when you only need one result because it stops searching after finding the first match.
Code Solution
SolutionRead Only
// find() - returns cursor to multiple documents
db.users.find({ age: { $gt: 25 } })
// Returns: cursor to all users older than 25
// findOne() - returns single document
db.users.findOne({ name: "Alice" })
// Returns: { _id: 1, name: "Alice", age: 30 }