CRUD
find() and findOne()
Reading documents, cursors versus a single result, and the first queries you should be able to write cold.
find() returns a cursor over every match. findOne() returns one document or null. Both take a filter. Both can take a projection — the next lesson.
db.users.find({ city: "Bangalore" }){ _id: ObjectId("64a1b2c3d4e5f6a7b8c90001"), name: "Rahul", city: "Bangalore", ... }
{ _id: ObjectId("64a1b2c3d4e5f6a7b8c90002"), name: "Priya", city: "Bangalore", ... }db.users.findOne({ email: "rahul@example.com" })The cursor is not an array
In mongosh, find() looks like it returned an array because the shell prints the first batch. In Node.js you get a cursor. Iterate it, or call toArray() when the result set is small enough to hold in memory.
const user = await users.findOne({ city: "Bangalore" });
const list = await users.find({ city: "Bangalore" }).toArray();Several keys in one filter are an implicit AND: { city: "Bangalore", isActive: true }. Comparison operators ($gt, $in, …) are the next module. One you will use immediately:
db.users.find({ age: { $gt: 25 } })Interview question
What is the difference between find() and findOne()?
find() returns a cursor you iterate; findOne() returns one document or null. findOne is find with a limit of one, and it unwraps the result for you. In Node.js you must iterate or toArray() a find() cursor; the shell hides that.
Practice
Write these against the seeded users collection.