Tablux

Tablux › Guides › MongoDB query examples

Guide

MongoDB query examples: a practical mongosh cookbook

The everyday MongoDB queries are find() with a filter document, sort() and limit(), countDocuments(), distinct(), aggregate() pipelines for grouping and joins, and updateOne/updateMany and deleteOne/deleteMany for changes. Below are copyable examples of each, all run in mongosh against one realistic orders collection, with the gotchas that catch people out.

The sample data

Every example uses a shop's orders collection, plus customers and products for joins and updates. One order:

{
  _id: ObjectId("6740a1c2e4b0a1b2c3d4e5f6"),
  orderNo: 58213,
  customerId: 1042,
  status: "delivered",
  orderedAt: ISODate("2026-10-14T09:31:00Z"),
  shipTo: { country: "GB", city: "Leeds" },
  items: [
    { sku: "TENT-RL2P", name: "Ridgeline 2P tent", category: "Tents", qty: 1, price: 249 },
    { sku: "STOVE-ALP", name: "Alpine stove", category: "Cooking", qty: 2, price: 39 }
  ],
  tags: ["gift"],
  total: 327
}

A customer is { _id: 1042, name: "Maya Patel", email: "[email protected]", tier: "gold" } and a product is { _id: "TENT-RL2P", name: "Ridgeline 2P tent", stock: 14 }. The examples work in current mongosh against MongoDB 6.0 or later; $dateTrunc needs 5.0 or later.

Equality and comparison

A filter is a document of field conditions. Fields listed together must all match.

db.orders.find({ status: "delivered" })

db.orders.find({ status: "delivered", "shipTo.country": "GB" })

Nested fields use dot notation, and the key must be quoted. Comparison operators take a value:

db.orders.find({ total: { $gte: 100, $lt: 500 } })

db.orders.find({ status: { $in: ["pending", "processing"] } })

db.orders.find({ status: { $ne: "cancelled" } })

db.orders.find({
  orderedAt: { $gte: ISODate("2026-10-01T00:00:00Z"), $lt: ISODate("2026-11-01T00:00:00Z") }
})

Dates must be compared as dates. { orderedAt: { $gte: "2026-10-01" } } compares against a string and matches nothing in a field that holds dates. A half-open range ($gte start, $lt next month) never misses the last day.

AND, OR, NOT and missing fields

Conditions in one document are an implicit AND. Use $or for alternatives, and an explicit $and only when you need two conditions with the same key, such as two $or clauses:

db.orders.find({ $or: [{ status: "pending" }, { total: { $gt: 1000 } }] })

db.orders.find({
  $and: [
    { $or: [{ status: "pending" }, { status: "processing" }] },
    { $or: [{ "shipTo.country": "GB" }, { tags: "express" }] }
  ]
})

$not wraps an operator expression or a regex, and it also matches documents where the field is missing. So do $ne and $nin:

db.orders.find({ total: { $not: { $gt: 500 } } })

db.orders.find({ "shipTo.country": { $nin: ["GB", "IE"] } })

db.orders.find({ "shipTo.country": { $exists: false } })

db.orders.find({ "shipTo.country": null })

The third query finds orders with no country at all; the fourth finds those where it is missing or explicitly null. If you mean "total is 500 or less", write { $lte: 500 }, which skips documents without a total.

Arrays

A plain value matches if any element equals it. $all wants every listed value; $size wants an exact length (it accepts no ranges):

db.orders.find({ tags: "gift" })

db.orders.find({ tags: { $all: ["gift", "express"] } })

db.orders.find({ items: { $size: 1 } })

For arrays of documents, $elemMatch makes several conditions apply to the same element. Compare these two:

db.orders.find({ items: { $elemMatch: { category: "Tents", qty: { $gte: 2 } } } })

db.orders.find({ "items.category": "Tents", "items.qty": { $gte: 2 } })

The first finds orders with two or more tents. The second also matches one tent plus two stoves, because each condition can be met by a different element.

Regex

db.customers.find({ email: /@example\.com$/ })

db.orders.find({ "items.name": /^ridgeline/i })

A case-sensitive regex anchored with ^ can use an index efficiently. A case-insensitive one (/i) or one without an anchor has to check every index key or document, so on a large collection store a lower-cased copy of the field or use a collation-aware index instead.

Projection, sort, limit and skip

The second argument of find() picks fields. Use 1 to include, or 0 to exclude, but don't mix them except for _id:

db.orders.find(
  { status: "delivered" },
  { orderNo: 1, total: 1, "shipTo.country": 1, _id: 0 }
)

The newest 20 orders with a total over 100, then the third page of them:

db.orders.find({ total: { $gt: 100 } }).sort({ orderedAt: -1 }).limit(20)

db.orders.find({ total: { $gt: 100 } }).sort({ orderedAt: -1 }).skip(40).limit(20)

skip() still walks past every skipped document, so deep pages get slower. For long lists, page by range instead: remember the last orderedAt you showed and ask for { orderedAt: { $lt: lastSeen } }. Sort on a field with an index, and add _id to the sort if values can tie.

Counting and distinct values

db.orders.countDocuments({ status: "pending" })

db.orders.estimatedDocumentCount()

db.orders.distinct("shipTo.country")

db.orders.distinct("items.category", { status: "delivered" })

countDocuments() runs the filter and is exact. estimatedDocumentCount() reads collection metadata, so it is fast but takes no filter. The older count() is deprecated in mongosh.

Aggregation pipelines

Revenue and order count by status for October, largest first:

db.orders.aggregate([
  { $match: { orderedAt: { $gte: ISODate("2026-10-01T00:00:00Z"), $lt: ISODate("2026-11-01T00:00:00Z") } } },
  { $group: { _id: "$status", orders: { $sum: 1 }, revenue: { $sum: "$total" } } },
  { $sort: { revenue: -1 } }
])

Revenue by month. $dateTrunc returns a date (the first instant of the month), which sorts and charts well; $dateToString with format: "%Y-%m" gives a label like 2026-10 instead:

db.orders.aggregate([
  { $match: { status: { $ne: "cancelled" } } },
  { $group: {
      _id: { $dateTrunc: { date: "$orderedAt", unit: "month", timezone: "Europe/London" } },
      revenue: { $sum: "$total" },
      orders: { $sum: 1 }
  } },
  { $sort: { _id: 1 } }
])

Best-selling products. $unwind turns each order into one document per line item:

db.orders.aggregate([
  { $match: { status: "delivered" } },
  { $unwind: "$items" },
  { $group: {
      _id: "$items.sku",
      name: { $first: "$items.name" },
      units: { $sum: "$items.qty" },
      revenue: { $sum: { $multiply: ["$items.qty", "$items.price"] } }
  } },
  { $sort: { units: -1 } },
  { $limit: 10 }
])

A join with $lookup: pending orders with the customer's email. $lookup always returns an array, so $unwind it when you expect one match:

db.orders.aggregate([
  { $match: { status: "pending" } },
  { $lookup: { from: "customers", localField: "customerId", foreignField: "_id", as: "customer" } },
  { $unwind: "$customer" },
  { $project: { _id: 0, orderNo: 1, total: 1, email: "$customer.email", lines: { $size: "$items" } } }
])

Put $match first so the pipeline can use an index and carries fewer documents. $unwind drops orders with no matching customer; add preserveNullAndEmptyArrays: true to keep them.

Inserts and updates

db.orders.insertOne({
  orderNo: 58990, customerId: 1042, status: "pending",
  orderedAt: new Date(), shipTo: { country: "GB", city: "York" },
  items: [{ sku: "BAG-CDR30", name: "Cedar 30L pack", category: "Backpacks", qty: 1, price: 89 }],
  tags: [], total: 89
})

Update operators change fields in place. Without one, updateOne refuses the update; replaceOne is the call that swaps a whole document.

db.orders.updateOne(
  { orderNo: 58990 },
  { $set: { status: "shipped", shippedAt: new Date() } }
)

db.orders.updateOne({ orderNo: 58990 }, { $addToSet: { tags: "express" } })

db.orders.updateOne({ orderNo: 58990 }, { $unset: { shippedAt: "" } })

db.products.updateOne({ _id: "TENT-RL2P" }, { $inc: { stock: -1 } })

$push appends even if the value is already there; $addToSet doesn't. To keep only the latest five notes:

db.orders.updateOne(
  { orderNo: 58990 },
  { $push: { notes: { $each: [{ at: new Date(), text: "Left with neighbour" }], $slice: -5 } } }
)

Cancel stale pending orders in one go:

db.orders.updateMany(
  { status: "pending", orderedAt: { $lt: ISODate("2026-10-01T00:00:00Z") } },
  { $set: { status: "cancelled" } }
)

An upsert inserts when nothing matches. A daily counter is the classic case:

db.dailyStats.updateOne(
  { day: "2026-11-25" },
  { $inc: { orders: 1, revenue: 89 } },
  { upsert: true }
)

Deletes, and the empty filter

db.orders.deleteOne({ orderNo: 58990 })

db.orders.deleteMany({ status: "cancelled", orderedAt: { $lt: ISODate("2025-01-01T00:00:00Z") } })

An empty filter matches every document. db.orders.deleteMany({}) deletes the whole collection's contents and db.orders.updateMany({}, …) changes every order. Before any multi-document write, run countDocuments() with the same filter and check the number:

db.orders.countDocuments({ status: "cancelled", orderedAt: { $lt: ISODate("2025-01-01T00:00:00Z") } })

To empty a collection on purpose, drop() is faster but also removes its indexes.

Running these outside mongosh

MongoDB Compass has a filter bar, an aggregation builder and an embedded mongosh. Tablux, on Mac, iPhone and iPad, accepts these calls as typed: find with projection and chained sort, skip and limit, findOne, aggregate, countDocuments, estimatedDocumentCount, distinct, insertOne/insertMany, updateOne/updateMany, replaceOne and deleteOne/deleteMany. It parses them rather than running JavaScript, so variables and loops aren't available, and of the update options it supports upsert only (other options, such as collation or arrayFilters, are refused rather than ignored). A deleteMany or updateMany with an empty filter is flagged before it runs, and on a production connection you type the connection's name to go ahead.

Questions

How do I query a nested field in MongoDB?

Use dot notation in quotes, for example db.orders.find({ "shipTo.country": "GB" }). For arrays of documents, use $elemMatch when several conditions must hold for the same element.

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

find() filters, projects and sorts documents as they are stored. aggregate() runs a pipeline of stages that can reshape, group, join with $lookup and compute new fields.

How do I count documents that match a filter?

db.collection.countDocuments(filter). It is exact and accepts any query. estimatedDocumentCount() is faster but counts the whole collection from metadata and takes no filter.

What does deleteMany({}) do?

It deletes every document in the collection, because an empty filter matches everything. updateMany({}, …) likewise changes every document. Check with countDocuments() and the same filter first.

How do I do a case-insensitive search in MongoDB?

Use a regex with the i flag, such as { name: /^ridgeline/i }. It cannot use an index efficiently, so for large collections store a lower-cased copy of the field or use a case-insensitive collation index.

Updated 2026-11-25