Explain the difference between find() and findOne() methods.

Beginner

Answer

find():

  • Returns a cursor to all matching documents
  • Returns multiple documents
  • Lazy evaluation - documents loaded as needed
  • Can be chained with other methods

findOne():

  • Returns the first matching document
  • Returns a single document object or null
  • Immediately executes and returns result
  • Cannot be chained with cursor methods
// find() - returns cursor
const cursor = db.users.find({age: {$gte: 25}})
cursor.forEach(doc => print(doc.name))

// findOne() - returns document
const user = db.users.findOne({email: "john@email.com"})
if (user) {
  print(user.name)
}