MongoDB Queries, Projection, Sort, and Pagination

Use filters, logical operators, projections, sorting, skip, and limit to shape query results efficiently.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Filter patterns
Comparison operators
db.orders.find({ total: { $gte: 100, $lte: 500 } })

# Filter with range operators.

Match a list of values
db.orders.find({ status: { $in: ["paid", "shipped"] } })

# Filter using `$in`.

Combine clauses with $or
db.orders.find({ $or: [{ priority: "high" }, { total: { $gt: 1000 } }] })

# Match one of several conditions.

Check field existence
db.orders.find({ shipped_at: { $exists: false } })

# Find documents that have or do not have a field.

Regex match
db.users.find({ email: /@example\.com$/i })

# Search string values with a regular expression.

## Projection, sort, and page
Project selected fields
db.users.find({ active: true }, { name: 1, email: 1, _id: 0 })

# Return only specific fields from matches.

Sort newest first
db.orders.find().sort({ created_at: -1 })

# Sort descending on a field.

Limit result size
db.orders.find().sort({ created_at: -1 }).limit(20)

# Return only a fixed number of documents.

Offset pagination
db.orders.find().sort({ created_at: -1 }).skip(40).limit(20)

# Page through results with skip and limit.

Cursor-style pagination idea
db.orders.find({ _id: { $lt: ObjectId("65f0c8d4d95f1b2a3c4d5e6f") } }).sort({ _id: -1 }).limit(20)

# Use a stable sort key such as `_id` or a timestamp.

Recommended next

No recommendations yet.