Querying Document Databases
1. Using Document Query Operators
| Operator | Use |
|---|---|
| $eq, $ne, $gt, $lt, $gte, $lte | Comparison |
| $in, $nin | Set membership |
| $exists, $type | Field presence/type |
| $regex | Pattern match |
| $elemMatch | Array element matching |
| $expr | Use aggregation expressions in query |
2. Filtering Nested Fields
Example: Nested Filter
db.users.find({ "addresses.city": "London" });
db.orders.find({ items: { $elemMatch: { sku: "A1", qty: { $gt: 2 } } } });
3. Performing Aggregation Pipelines
Example: Aggregation Pipeline
db.orders.aggregate([
{ $match: { status: "paid", created_at: { $gte: ISODate("2026-01-01") } } },
{ $group: { _id: "$customer_id", total: { $sum: "$amount" }, n: { $sum: 1 } } },
{ $sort: { total: -1 } },
{ $limit: 10 }
]);
| Stage | Use |
|---|---|
| $match | Filter (early for index use) |
| $project | Reshape fields |
| $group | Aggregate |
| $lookup | Left outer join |
| $unwind | Explode arrays |
| $facet | Multiple sub-pipelines |
4. Joining Documents
Example: $lookup
db.orders.aggregate([
{ $lookup: {
from: "customers", localField: "customer_id",
foreignField: "_id", as: "customer" } },
{ $unwind: "$customer" }
]);
5. Sorting and Pagination
| Pattern | Detail |
|---|---|
| skip + limit | Simple but slow for deep pages |
| Cursor (range) | WHERE _id > lastId LIMIT N |
| Compound sort + index | Must match index order |
| Total count | Often skipped on infinite scroll |
6. Using Map-Reduce
| Aspect | Detail |
|---|---|
| Status | Deprecated in MongoDB; prefer aggregation |
| Use case | Custom JS aggregation |
| Performance | Slower than aggregation pipeline |
7. Performing Text Search
Example: Text Search
db.articles.createIndex({ title: "text", body: "text" });
db.articles.find(
{ $text: { $search: "graph database neo4j" } },
{ score: { $meta: "textScore" } }
).sort({ score: { $meta: "textScore" } });
8. Using Geospatial Queries
| Operator | Use |
|---|---|
| $near / $nearSphere | Sorted by distance |
| $geoWithin | Inside polygon / circle |
| $geoIntersects | Geometries that intersect |
| Index | 2dsphere for GeoJSON |
9. Optimizing Document Queries
| Tip | Detail |
|---|---|
| ESR rule | Equality, Sort, Range fields in compound index |
| Covered queries | Project only indexed fields |
| explain('executionStats') | Inspect plan + docs examined |
| Avoid $where / JS | No index use |
| Projection | Limit returned fields |
10. Analyzing Query Performance
| Tool | Detail |
|---|---|
| db.coll.explain() | Query plan stages |
| Profiler (system.profile) | Slow ops capture |
| Atlas Performance Advisor | Index suggestions |
| currentOp / killOp | Inspect/kill running ops |
| Metrics | opcounters, slow queries, scanned/returned ratio |