On this page
  1. CRUD & Aggregation Pipeline
  2. Contents
  3. Atomic Document Updates
  4. Aggregation Pipeline Stages

CRUD & Aggregation Pipeline

Prev: BSON Documents & Schema Design | Up: mongodb | Next: Indexes, Replica Sets & Transactions
Rel: SQL Aggregations, CTEs & Windows
Ref: MongoDB — Aggregation Operations
Tags: #public #databases #mongodb #nosql #aggregation


Contents


Atomic Document Updates

Single-document writes in MongoDB are always atomic. Use atomic operators ($set, $inc, $push, $addToSet) instead of read-modify-replace cycles:

db.users.updateOne(
  { _id: userId },
  {
    $set: { lastSeenAt: new Date() },
    $inc: { loginCount: 1 },
    $addToSet: { roles: "editor" },
  }
);

Aggregation Pipeline Stages

Pipelines transform documents through ordered stages. Place $match and $sort as early as possible so they can use indexes before $group or $lookup:

db.orders.aggregate([
  { $match: { status: "paid" } },
  {
    $group: {
      _id: "$userId",
      orderCount: { $sum: 1 },
      totalCents: { $sum: "$totalCents" },
    },
  },
  { $sort: { totalCents: -1 } },
  { $limit: 10 },
]);

Linked from

Related notes