Skip to content
Sealpaste

Delete all recent work?

This removes the 0 items saved in this browser. Your settings stay.

Stop saving recent work?

New work won't be saved in this browser. The 0 items already saved can stay or go.

MongoDB Aggregation Formatter

Pipeline

Paste a pipeline, or

CtrlV paste · Ctrl↵ run now

mongosh
Ready
Ln 1, Col 1
Runs in your browser. Nothing you paste is uploaded unless you share it.

Format a MongoDB aggregation pipeline, read what each stage does, catch misplaced stages, get Node.js, Python, Java, Go or C# code

Paste a pipeline from mongosh, Compass, a log or your code. Get it indented, each stage explained in a comment, and the same pipeline as driver code.

How to use it

  1. Paste db.orders.aggregate([…]), a pipeline […] or one stage { … }, in mongosh syntax or Extended JSON .
  2. Keep Explain stages on for a comment above each stage; choose mongosh or a driver language above the editor.
  3. Copy the result or download it. Problems MongoDB would refuse, like $out before the last stage, are listed under it.

Examples

One line to readable, each stage explained

Input
db.users.aggregate([{ $match: { age: { $gte: 18 } } }, { $group: { _id: "$country", users: { $sum: 1 } } }, { $sort: { users: -1 } }])
Result
db.users.aggregate([
  // 1. $match: Keeps the documents where age is at least 18.
  { $match: { age: { $gte: 18 } } },
  // 2. $group: Groups documents by country; each group gets users = the number of documents.
  { $group: { _id: '$country', users: { $sum: 1 } } },
  // 3. $sort: Sorts by users descending.
  { $sort: { users: -1 } }
])

Short stages stay on one line; a stage too wide for 80 columns opens up, as Prettier does.

The same pipeline in PyMongo

Input
[{ $match: { status: "A" } }, { $group: { _id: "$cust_id", total: { $sum: "$amount" } } }]
Result
import os

from pymongo import MongoClient

client = MongoClient(os.environ["MONGODB_URI"])
collection = client["test"]["collection"]

pipeline = [
    {"$match": {"status": "A"}},
    {"$group": {"_id": "$cust_id", "total": {"$sum": "$amount"}}},
]

for doc in collection.aggregate(pipeline):
    print(doc)

With Python chosen and Explain stages off. The collection name comes from db.<name>.aggregate when you paste one.

A misspelled stage

Input
[{ $mtach: { status: "A" } }]
Result
Stage 1: $mtach is not an aggregation stage. Did you mean $match?

What it reads

Anything a MongoDB pipeline is written as: the whole db.<collection>.aggregate([…], { … }) call or db.getCollection("…").aggregate(…), a bare array of stages, or a single stage. Unquoted keys, single quotes, comments, trailing commas and mongosh’s helpers (ObjectId, ISODate, NumberLong, NumberDecimal, UUID, BinData, Timestamp, /regex/) are read, and so is Extended JSON ({"$oid": …}, {"$date": …}).

Each stage must be a document with exactly one key, a stage MongoDB knows; a misspelled one is named with the closest real stage. Numbers keep their digits: a 64-bit NumberLong is never rounded.

Driver code

Each language gets a short program that connects with MONGODB_URI, runs the pipeline and prints the results, written with that driver’s own BSON types:

  • Node.js (mongodb package): new ObjectId(…), new Date(…), Long, Decimal128, regex literals.
  • Python (PyMongo): dictionaries with ObjectId, timezone-aware datetime, Int64, Decimal128 and Regex; aggregate() options as keyword arguments.
  • Java (sync driver): new Document(…).append(…) chains in Arrays.asList, long values with L, Decimal128 from BigDecimal.
  • Go (driver v2): mongo.Pipeline of bson.D with Key and Value named, time.Date for dates, a small must() helper for ids and decimals.
  • C# (.NET driver): new BsonDocument initializers in a BsonDocument[] and AggregateOptions for allowDiskUse, batchSize, maxTimeMS, comment and hint.

Sources: MongoDB: aggregation stages, MongoDB: db.collection.aggregate()

Checks

Under the result, a list of what MongoDB would refuse or what changes the output:

  • $out and $merge anywhere but last; $geoNear, $search, $vectorSearch, $documents and the other first-only stages anywhere but first.
  • $limit, $skip and $sample without a whole number above 0, a $group without _id, $sort values other than 1 and -1.
  • $count with a $ or a dot in its name, $unwind without a $ path, $lookup without as or without localField and foreignField (or a pipeline).
  • A $project that mixes 1 and 0 on fields other than _id, and $where inside $match.

Questions

Does it run my pipeline?
No. It reads and rewrites the text; nothing connects to a database, so the explanations describe what each stage does, not your data. Run the result in mongosh or Compass to see documents.
Can I paste it back into Compass?
Yes. Compass’s pipeline text view takes the array of stages: paste a bare […] here, choose mongosh, and the result stays a bare array in mongosh syntax. Turn Explain stages off if you don’t want the comments.
Is my pipeline uploaded?
No. Everything runs in your browser, so your pipeline stays on your device. Nothing you paste is uploaded unless you share a result, which is locked with your password first. Formatting and code generation run in a worker in this tab.

Related tools