Q1. How do you find all documents in a collection?
Use the find() method without parameters:
db.users.find()
This returns a cursor to all documents. To iterate results, you can use db.users.find().pretty()
for formatted output in mongosh.Q2. How do you find a single document?
Use findOne() to retrieve the first document matching a query:
db.users.findOne({ name: "John" })
If no criteria given, it returns the first document in the collection. This method returns a document directly, not a cursor.Q3. How do you find documents with a filter?
Pass a query filter object to find():
db.users.find({ age: { $gt: 25 } })
This returns all users with age greater than 25. You can combine conditions: db.users.find({ age: { $gt: 25 }, city: "NYC" })
Q4. How do you limit the fields returned?
Use projection as the second argument to find():
db.users.find({ age: 30 }, { name: 1, email: 1, _id: 0 })
1 includes the field, 0 excludes it. The _id field is included by default unless explicitly excluded.Q5. What is a cursor in MongoDB?
A cursor is an object that points to the result set of a query. The find() method returns a cursor, which allows you to iterate over documents lazily. In mongosh, the shell automatically iterates up to 20 documents. You can use cursor methods like
.limit(), .skip(), .sort()
to control the output.