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

Common selectors for exact matches and operator-based filtering.

Comparison operators

Filter with range operators.

javascriptANYmongodbquerycomparison
javascript
db.orders.find({ total: { $gte: 100, $lte: 500 } })
Notes

Range filters are common for prices, scores, and timestamps.

Match a list of values

Filter using `$in`.

javascriptANYmongodbqueryin
javascript
db.orders.find({ status: { $in: ["paid", "shipped"] } })
Notes

Useful for dashboard queries and status subsets.

Combine clauses with $or

Match one of several conditions.

javascriptANYmongodbqueryor
javascript
db.orders.find({ $or: [{ priority: "high" }, { total: { $gt: 1000 } }] })
Notes

Logical operators help express more realistic query conditions.

Check field existence

Find documents that have or do not have a field.

javascriptANYmongodbexistsquery
javascript
db.orders.find({ shipped_at: { $exists: false } })
Notes

Helpful when auditing incomplete data or backfills.

Regex match

Search string values with a regular expression.

javascriptANYmongodbregexquery
javascript
db.users.find({ email: /@example\.com$/i })
Notes

Regex is flexible but can be expensive without the right patterns and indexes.

Projection, sort, and page

Return only the fields you need and keep results stable.

Project selected fields

Return only specific fields from matches.

javascriptANYmongodbprojectionfind
javascript
db.users.find({ active: true }, { name: 1, email: 1, _id: 0 })
Notes

Projection can reduce payload size and improve clarity.

Sort newest first

Sort descending on a field.

javascriptANYmongodbsort
javascript
db.orders.find().sort({ created_at: -1 })
Notes

`-1` is descending and `1` is ascending.

Limit result size

Return only a fixed number of documents.

javascriptANYmongodblimit
javascript
db.orders.find().sort({ created_at: -1 }).limit(20)
Notes

Limit is a basic building block for API endpoints and dashboards.

Offset pagination

Page through results with skip and limit.

javascriptANYmongodbpaginationskiplimit
javascript
db.orders.find().sort({ created_at: -1 }).skip(40).limit(20)
Notes

Offset pagination is easy to understand but can become less efficient for very large offsets.

Cursor-style pagination idea

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

javascriptANYmongodbpaginationcursor
javascript
db.orders.find({ _id: { $lt: ObjectId("65f0c8d4d95f1b2a3c4d5e6f") } }).sort({ _id: -1 }).limit(20)
Notes

Cursor pagination usually scales better than repeated large skips.

Recommended next

No recommendations yet.