Querying Document Databases

1. Using Document Query Operators

OperatorUse
$eq, $ne, $gt, $lt, $gte, $lteComparison
$in, $ninSet membership
$exists, $typeField presence/type
$regexPattern match
$elemMatchArray element matching
$exprUse 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 }
]);
StageUse
$matchFilter (early for index use)
$projectReshape fields
$groupAggregate
$lookupLeft outer join
$unwindExplode arrays
$facetMultiple 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

PatternDetail
skip + limitSimple but slow for deep pages
Cursor (range)WHERE _id > lastId LIMIT N
Compound sort + indexMust match index order
Total countOften skipped on infinite scroll

6. Using Map-Reduce

AspectDetail
StatusDeprecated in MongoDB; prefer aggregation
Use caseCustom JS aggregation
PerformanceSlower than aggregation pipeline
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

OperatorUse
$near / $nearSphereSorted by distance
$geoWithinInside polygon / circle
$geoIntersectsGeometries that intersect
Index2dsphere for GeoJSON

9. Optimizing Document Queries

TipDetail
ESR ruleEquality, Sort, Range fields in compound index
Covered queriesProject only indexed fields
explain('executionStats')Inspect plan + docs examined
Avoid $where / JSNo index use
ProjectionLimit returned fields

10. Analyzing Query Performance

ToolDetail
db.coll.explain()Query plan stages
Profiler (system.profile)Slow ops capture
Atlas Performance AdvisorIndex suggestions
currentOp / killOpInspect/kill running ops
Metricsopcounters, slow queries, scanned/returned ratio