Skip to content

CRUD

find() and findOne()

Reading documents, cursors versus a single result, and the first queries you should be able to write cold.

BeginnerAbout 5 minutes

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" })
Equality on a field. Same idea as WHERE city = 'Bangalore'.
{ _id: ObjectId("64a1b2c3d4e5f6a7b8c90001"), name: "Rahul", city: "Bangalore", ... }
{ _id: ObjectId("64a1b2c3d4e5f6a7b8c90002"), name: "Priya", city: "Bangalore", ... }
Every matching user — the shell iterates the cursor for you
db.users.findOne({ email: "rahul@example.com" })
One document, or null

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();
Node.js

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 } })
age strictly greater than 25

Interview question

What is the difference between find() and findOne()?

Think about it first.

Practice

Write these against the seeded users collection.