Skip to main content

Databases · Intermediate · 26 min

Query and index documents in MongoDB 9 with mongosh

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · MongoDB 9.0.8

You will load 50,000 delivery orders into MongoDB 9.0, query and update them in mongosh, prove a compound index with explain, add partial and TTL indexes, guard the collection with $jsonSchema validation and summarise it with a first aggregation.

On this page

A delivery service answers the same few questions all day: which orders is this courier carrying, what did this city deliver this month, which big orders went out in Lagos most recently. In MongoDB each order is one document holding its items, totals and status together, so most of those questions are a single query. Whether that query takes a millisecond or reads every document on disk depends on the indexes you give it.

In this tutorial you generate 50,000 realistic delivery orders across six cities, import them with mongoimport, and work in mongosh. You filter, project and sort; use $in, $gte and $elemMatch; change orders with $set, $inc and $push; and keep a running counter with an upsert. Then you read explain("executionStats") before and after a compound index, add a partial index and a TTL index, lock the collection's shape down with $jsonSchema, and finish with an aggregation that totals November's deliveries by city.

You work as appuser, the account limited to appdb that you created in the install tutorial. The generator uses a fixed seed, so your data matches the numbers quoted here exactly.

Step 1 · Generate and import 50,000 orders

Make a folder for the files in this tutorial:

Bash
mkdir -p ~/mongo-orders-demo
cd ~/mongo-orders-demo

Save the generator. It is plain JavaScript that mongosh can run without a database connection, because mongosh runs on Node.js and can load built-in modules such as fs. Each order has an id, a customer, a city, a status, the time it was placed, one to four line items, a total in cents and, once a courier has it, a courier id. Dates are written as {"$date": "..."}, the Extended JSON form that mongoimport turns into real BSON dates.

Bash
cat > gen-orders.js <<'JS'
// Writes 50,000 delivery orders to orders.json, one JSON document per line.
// The seed is fixed, so every run produces the same orders.
const fs = require('fs');

let seed = 20261118;
function rand() {
  seed = (seed + 0x6d2b79f5) | 0;
  let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
  t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
  return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
}
const pick = (list) => list[Math.floor(rand() * list.length)];
const pad = (n, width) => String(n).padStart(width, '0');

const cities = ['Lagos', 'Nairobi', 'Accra', 'Kampala', 'Kigali', 'Johannesburg'];
const products = [
  ['RICE-5KG', 1200], ['COOKING-OIL-2L', 850], ['SOLAR-LAMP', 2400],
  ['PHONE-CHARGER', 900], ['POWER-BANK', 3200], ['SOAP-6PK', 450],
  ['TEA-500G', 380], ['NAPPIES-L', 1500], ['WATER-12PK', 600],
  ['DESK-FAN', 4200], ['TORCH', 700], ['SIM-STARTER', 150],
];
const start = Date.UTC(2026, 8, 1); // 1 September 2026
const lines = [];

for (let i = 1; i <= 50000; i++) {
  const r = rand();
  const status = r < 0.70 ? 'delivered' : r < 0.78 ? 'out_for_delivery' : r < 0.90 ? 'placed' : 'cancelled';
  const items = [];
  const count = 1 + Math.floor(rand() * 4);
  for (let j = 0; j < count; j++) {
    const [sku, price] = pick(products);
    items.push({ sku, qty: 1 + Math.floor(rand() * 3), price });
  }
  const order = {
    _id: 'ORD-' + pad(i, 5),
    customerId: 'CUS-' + pad(1 + Math.floor(rand() * 5000), 4),
    city: pick(cities),
    status,
    placedAt: { $date: new Date(start + Math.floor(rand() * 91 * 86400) * 1000).toISOString() },
    items,
    totalCents: items.reduce((sum, it) => sum + it.qty * it.price, 0),
  };
  if (status === 'delivered' || status === 'out_for_delivery') {
    order.courierId = 'CR-' + pad(1 + Math.floor(rand() * 40), 2);
  }
  lines.push(JSON.stringify(order));
}

fs.writeFileSync('orders.json', lines.join('\n') + '\n');
console.log('Wrote ' + lines.length + ' orders to orders.json');
JS
mongosh --nodb --quiet gen-orders.js
wc -l orders.json

The script prints Wrote 50000 orders to orders.json, and wc counts 50000 lines in a file of about 14 MB. Now import it into the orders collection of appdb. With --username and no --password, mongoimport asks for the password, so it never lands in your shell history:

Bash
mongoimport --host 127.0.0.1 --port 27017 --username appuser --authenticationDatabase appdb \
  --db appdb --collection orders --file orders.json

The last line reads 50000 document(s) imported successfully. 0 document(s) failed to import. If you run the import a second time, every document fails with a duplicate key error on _id, because the ids are already there. Adding --drop deletes the whole orders collection and its indexes before importing, so use it only when you mean to start that collection again.

Check it worked

Open a shell as appuser and keep it open for the rest of the tutorial. Start it from ~/mongo-orders-demo, because a later step reads a file from that folder:

Bash
cd ~/mongo-orders-demo
mongosh "mongodb://appuser@127.0.0.1:27017/appdb" -p

At the appdb> prompt, count the orders and look at the first one:

JavaScript
db.orders.countDocuments()
db.orders.findOne({ _id: "ORD-00001" })

The count is 50000. The first order is a delivered Kigali order with one SOLAR-LAMP, totalCents: 2400, and a placedAt shown as ISODate('2026-11-05T10:05:46.000Z'). The ISODate wrapper tells you the date was stored as a date, not as a string, which the range queries and the TTL index later depend on.

Step 2 · Filter, project and sort

A filter is a document of the fields you want to match. Count the delivered orders in Nairobi:

JavaScript
db.orders.countDocuments({ city: "Nairobi", status: "delivered" })

The answer is 5904. To get the documents themselves, use find with the same filter. A second argument, the projection, picks which fields come back. Sort by total, largest first, and keep the top three:

JavaScript
db.orders.find(
  { city: "Nairobi", status: "delivered" },
  { customerId: 1, totalCents: 1, placedAt: 1 }
).sort({ totalCents: -1, _id: 1 }).limit(3)

The projection returns _id unless you add _id: 0, and leaves out everything you did not name. That matters on a phone app: a list screen on a low-end Android handset over prepaid mobile data needs the three fields it shows, not every line item of every order.

The two top orders both total 33300 cents. Without the second sort key, MongoDB is free to return tied documents in any order, and page two of a list could repeat or skip an order. Adding _id: 1 as a tie-breaker makes the order stable.

Check it worked

The three documents come back as ORD-40652 (33300), ORD-44286 (33300) and ORD-19055 (31950), each with only _id, customerId, placedAt and totalCents. If you see items or city, check the projection's braces.

Step 3 · Use query operators: $in, $gte and $elemMatch

Operators start with $ and go where a plain value would. $in matches any value in a list and $gte means greater than or equal. Count the orders still waiting to be picked up in Accra or Kigali that are worth at least 5000 cents:

JavaScript
db.orders.countDocuments({
  city: { $in: ["Accra", "Kigali"] },
  status: "placed",
  totalCents: { $gte: 5000 }
})

The answer is 1111. Fields in one filter are combined with AND; $in gives you OR within one field.

Arrays need more care. Suppose you want orders that contain three or more solar lamps. This looks right but is not:

JavaScript
db.orders.countDocuments({ "items.sku": "SOLAR-LAMP", "items.qty": { $gte: 3 } })

It returns 6410. Each condition is checked against the array on its own, so an order with one solar lamp and three bags of rice matches: some item is a lamp, and some item has a quantity of three. $elemMatch makes both conditions apply to the same item:

JavaScript
db.orders.countDocuments({ items: { $elemMatch: { sku: "SOLAR-LAMP", qty: { $gte: 3 } } } })

Check it worked

The $elemMatch count is 3403, roughly half the dotted version's 6410. Whenever two conditions describe one array element, reach for $elemMatch; a single condition such as { "items.sku": "TORCH" } does not need it.

Step 4 · Update orders and keep a counter with an upsert

Order ORD-00005 is out for delivery in Lagos. The courier knocks and nobody answers. Record the failed attempt: $inc adds to a number (and creates the field at 1 when it is missing) and $push appends to an array (creating it too). Putting status in the filter means the update does nothing if another process has already changed the order:

JavaScript
db.orders.updateOne(
  { _id: "ORD-00005", status: "out_for_delivery" },
  {
    $inc: { deliveryAttempts: 1 },
    $push: { timeline: { at: new Date(), note: "Customer not home, retry tomorrow" } }
  }
)

The reply shows matchedCount: 1 and modifiedCount: 1. The next day the delivery succeeds. $set writes fields and leaves the rest of the document alone:

JavaScript
db.orders.updateOne(
  { _id: "ORD-00005", status: "out_for_delivery" },
  {
    $set: { status: "delivered", deliveredAt: new Date() },
    $inc: { deliveryAttempts: 1 },
    $push: { timeline: { at: new Date(), note: "Delivered to customer" } }
  }
)

An upsert updates a document if the filter matches one and inserts it otherwise. It suits counters, such as a dashboard tile of deliveries per city per day. Run this twice:

JavaScript
db.daily_city_counts.updateOne(
  { _id: "2026-11-30:Lagos" },
  { $inc: { delivered: 1 }, $setOnInsert: { firstSeenAt: new Date() } },
  { upsert: true }
)

The first run creates the collection and the document, and replies with upsertedCount: 1. The second matches it and replies with modifiedCount: 1. $setOnInsert only writes on the insert, so firstSeenAt keeps the time of the first run.

Check it worked

JavaScript
db.orders.findOne({ _id: "ORD-00005" }, { status: 1, deliveryAttempts: 1, timeline: 1 })
db.daily_city_counts.findOne()

The order shows status: 'delivered', deliveryAttempts: 2 and a timeline array with two entries. Its items are untouched. The counter document shows delivered: 2. If you run the first order update again now, it reports matchedCount: 0, because the order is no longer out for delivery.

Step 5 · Read a query plan, then add a compound index

The operations dashboard asks for the ten most recent delivered Lagos orders worth 20000 cents or more. Paste this helper first. It runs explain("executionStats") and keeps the parts worth reading: the stages of the winning plan, how many index keys and documents MongoDB examined, and how many it returned:

JavaScript
function plan(cursor) {
  const e = cursor.explain("executionStats");
  const stages = JSON.stringify(e.queryPlanner.winningPlan).match(/"stage":"[A-Z_]+"/g) || [];
  return {
    stages: stages.map((s) => s.slice(9, -1)),
    keysExamined: e.executionStats.totalKeysExamined,
    docsExamined: e.executionStats.totalDocsExamined,
    returned: e.executionStats.nReturned,
    ms: e.executionStats.executionTimeMillis
  };
}

plan(db.orders.find({ city: "Lagos", status: "delivered", totalCents: { $gte: 20000 } }).sort({ placedAt: -1 }).limit(10))

The stages include COLLSCAN and SORT, and docsExamined is 50000: MongoDB read every order, kept the matches, sorted them in memory and threw most away to return 10. At 50,000 documents that still feels quick. At five million it does not.

Build the index in the order MongoDB's equality, sort, range guideline describes: first the fields you match exactly (city, status), then the sort field (placedAt, in the direction you sort), then the range field (totalCents):

JavaScript
db.orders.createIndex(
  { city: 1, status: 1, placedAt: -1, totalCents: 1 },
  { name: "city_status_placedAt_total" }
)

plan(db.orders.find({ city: "Lagos", status: "delivered", totalCents: { $gte: 20000 } }).sort({ placedAt: -1 }).limit(10))

With the equality fields first, every matching key sits in one block of the index, already ordered by placedAt, so MongoDB walks it newest first and stops after ten hits. If totalCents came before placedAt, the matches would come out ordered by total, and MongoDB would have to sort them again in memory.

Check it worked

The second plan shows IXSCAN and FETCH (and LIMIT), with no COLLSCAN and no SORT. docsExamined and returned are both 10; keysExamined is higher, because the scan skips index entries under 20000 cents without fetching their documents. Run the query itself and the first three ids are ORD-14927, ORD-32046 and ORD-29786, all placed at the end of November.

Step 6 · Add a partial index and a TTL index

Couriers' phones ask "what am I carrying?" every few seconds. Only orders that are out for delivery ever answer that, about 8% of the collection. A partial index holds entries only for documents that match its filter, so it stays small and cheap to keep up to date:

JavaScript
db.orders.createIndex(
  { courierId: 1, placedAt: 1 },
  { name: "active_by_courier", partialFilterExpression: { status: "out_for_delivery" } }
)

plan(db.orders.find({ status: "out_for_delivery", courierId: "CR-07" }).sort({ placedAt: 1 }))
plan(db.orders.find({ courierId: "CR-07" }))

The first query uses active_by_courier and returns 100 orders after examining 100 documents. The second does not mention status, so MongoDB cannot be sure every match is in the index and falls back to COLLSCAN. A query uses a partial index only when its filter includes the index's filter condition.

A TTL index deletes documents once a date field is older than a set number of seconds. Use it for data that should not live forever, such as courier location pings. Create the collection with an index that expires pings after an hour, then insert three pings from two hours ago and one from now:

JavaScript
db.courier_pings.createIndex({ at: 1 }, { expireAfterSeconds: 3600 })

const twoHoursAgo = new Date(Date.now() - 2 * 3600 * 1000)
db.courier_pings.insertMany([
  { courierId: "CR-07", at: twoHoursAgo, lat: 6.4541, lng: 3.3947 },
  { courierId: "CR-07", at: twoHoursAgo, lat: 6.4550, lng: 3.3960 },
  { courierId: "CR-14", at: twoHoursAgo, lat: 6.5244, lng: 3.3792 },
  { courierId: "CR-14", at: new Date(), lat: 6.5250, lng: 3.3801 }
])

A background task removes expired documents every 60 seconds, so deletion is not instant. The field must hold a BSON date; a document whose at is a string or missing never expires.

Check it worked

JavaScript
db.orders.getIndexes().map((i) => i.name)
db.courier_pings.countDocuments()

The index list is [ '_id_', 'city_status_placedAt_total', 'active_by_courier' ]. The ping count starts at 4; run it again after a minute or two and it reads 1, the fresh ping from CR-14.

Step 7 · Enforce the order shape with $jsonSchema validation

Nothing yet stops a bug in your app from writing status: "lost" or an order with no items. A validator rejects such writes. Save the rules in a file, so the same schema can live next to your app code and in version control:

Bash
cat > ~/mongo-orders-demo/order-schema.json <<'JSON'
{
  "bsonType": "object",
  "required": ["_id", "customerId", "city", "status", "placedAt", "items", "totalCents"],
  "properties": {
    "customerId": { "bsonType": "string", "pattern": "^CUS-[0-9]{4}$" },
    "city": { "bsonType": "string" },
    "status": { "enum": ["placed", "out_for_delivery", "delivered", "cancelled"] },
    "placedAt": { "bsonType": "date" },
    "totalCents": { "bsonType": "number", "minimum": 0 },
    "items": {
      "bsonType": "array",
      "minItems": 1,
      "items": {
        "bsonType": "object",
        "required": ["sku", "qty", "price"],
        "properties": {
          "sku": { "bsonType": "string" },
          "qty": { "bsonType": "number", "minimum": 1 },
          "price": { "bsonType": "number", "minimum": 0 }
        }
      }
    }
  }
}
JSON

"bsonType": "number" accepts any numeric type. That matters because mongoimport stores whole numbers as 32-bit integers while mongosh sends numbers as doubles, and a schema that demands "int" would reject values typed in the shell.

A new validator only checks writes made after it is applied, so first confirm the existing data already passes. In your appuser shell, load the file and count documents that do not match:

JavaScript
const orderSchema = JSON.parse(require("fs").readFileSync("order-schema.json", "utf8"))
db.orders.countDocuments({ $nor: [{ $jsonSchema: orderSchema }] })

The answer is 0. Applying a validator uses the collMod command, which the readWrite role does not include. Rather than widen the app's own account, create a separate account for schema changes with the dbAdmin role on appdb. In a second terminal, log in as admin:

Bash
mongosh -u admin -p --authenticationDatabase admin
JavaScript
use appdb
db.createUser({
  user: "appmigrator",
  pwd: passwordPrompt(),
  roles: [{ role: "dbAdmin", db: "appdb" }]
})

Type exit, then connect as appmigrator from ~/mongo-orders-demo:

Bash
cd ~/mongo-orders-demo
mongosh "mongodb://appmigrator@127.0.0.1:27017/appdb" -p
JavaScript
const orderSchema = JSON.parse(require("fs").readFileSync("order-schema.json", "utf8"))
db.runCommand({
  collMod: "orders",
  validator: { $jsonSchema: orderSchema },
  validationLevel: "strict",
  validationAction: "error"
})

The reply is { ok: 1 }. strict checks every insert and update; error rejects a write that fails. Type exit and go back to the appuser shell.

Check it worked

As appuser, try to insert an order with a status the schema does not allow:

JavaScript
db.orders.insertOne({
  _id: "ORD-TEST1", customerId: "CUS-0001", city: "Lagos", status: "lost",
  placedAt: new Date(), items: [{ sku: "TORCH", qty: 1, price: 700 }], totalCents: 700
})

The shell prints MongoServerError: Document failed validation, followed by details something like schemaRulesNotSatisfied naming the status property and its enum. Change "lost" to "placed" and it would succeed. The collection still holds 50,000 orders.

Step 8 · Summarise November with an aggregation

An aggregation pipeline passes documents through stages in order. Total November's delivered orders by city: $match keeps delivered orders placed in November, $group makes one result per city with a count and a revenue sum, and $sort puts the biggest city first:

JavaScript
db.orders.aggregate([
  { $match: {
      status: "delivered",
      placedAt: { $gte: ISODate("2026-11-01T00:00:00Z"), $lt: ISODate("2026-12-01T00:00:00Z") }
  } },
  { $group: { _id: "$city", orders: { $sum: 1 }, revenueCents: { $sum: "$totalCents" } } },
  { $sort: { revenueCents: -1 } }
])

Put $match first. It cuts the documents down before the expensive stages run, and a $match at the start of a pipeline can use an index.

The month boundaries above are in UTC. Lagos is one hour ahead of UTC and Nairobi three, so an order placed at 00:30 on 1 December in Nairobi is still a November order in UTC. When a report must follow each city's local calendar, group with $dateTrunc and its timezone option (for example "Africa/Nairobi") instead of fixed UTC dates.

Check it worked

You get six documents. The first is { _id: 'Lagos', orders: 1944, revenueCents: 13392920 } and the last is Kigali with 1794 orders. Kampala comes second on revenue with fewer orders than Accra, which is the kind of detail a sorted summary shows and a raw count hides.

Step 9 · Clean up

These commands delete the three collections this tutorial created and the migration account. They leave appdb, appuser and the notes collection from the install tutorial in place. In the appuser shell:

JavaScript
db.orders.drop()
db.daily_city_counts.drop()
db.courier_pings.drop()

Each returns true. Dropping a collection also drops its indexes and its validator. As admin (mongosh -u admin -p --authenticationDatabase admin), remove the migration account:

JavaScript
db.getSiblingDB("appdb").dropUser("appmigrator")

Leave both shells with exit, then delete the demo folder:

Bash
cd ~
rm -rf ~/mongo-orders-demo

Check it worked

In a new appuser shell, db.getCollectionNames() no longer lists orders, daily_city_counts or courier_pings, and ls ~/mongo-orders-demo reports that the folder does not exist.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.