Skip to content

mongoexport for CSV/JSON pipelines: streaming exports without loading the host

Use mongoexport to stream MongoDB data into CSV/JSON pipelines feeding warehouses, BI tools, and downstream services — query filters, field selection, and the consistency caveats.

mongoexport writes documents from a MongoDB collection as JSON (one document per line) or CSV — the textual counterpart to mongodump’s BSON. It is the tool you reach for when an analyst needs “the orders table since Friday in CSV” or when a downstream pipeline expects newline-delimited JSON it can ingest. This article covers query-based exports, the field-selection rules for CSV, and the consistency caveats that bite when the source collection changes during the export.

How to verify

Run a small export and inspect the output:

mongoexport \
  --uri="mongodb://export:secret@mongo.example.internal:27017/shop?authSource=admin&readPreference=secondary" \
  --collection=orders \
  --query='{ "placedAt": { "$gte": { "$date": "2026-06-01T00:00:00Z" } } }' \
  --fields=_id,customerId,placedAt,amount,status \
  --type=csv \
  --out=/tmp/orders.csv
head -3 /tmp/orders.csv
wc -l /tmp/orders.csv

The first line of a CSV export is the field header. JSON output omits the header and writes one document per line in extended-JSON v2 form ({"_id": {"$oid": "..."}}).

What’s happening

mongoexport opens a cursor against the specified collection, applies the optional --query filter, projects the requested fields, and writes the result to stdout or a file. CSV mode requires --fields (an explicit list or --fieldFile) because flattening nested documents into columns is ambiguous; JSON mode preserves the document structure. Without --query, the entire collection is exported.

The export is not point-in-time consistent. A long-running export sees writes that arrive during the export — a new document inserted halfway through may or may not appear depending on cursor position. For consistent snapshots, either run against a backup secondary with readConcern: "snapshot" (mongoexport 100.x supports this) or wrap in a session and use snapshot reads.

Field paths use dot notation for nested fields (customer.address.city). Array elements use positional notation (tags.0). CSV exports flatten arrays into a single quoted string by default; use --jsonArray to wrap individual documents differently or write a custom transformation downstream.

The procedure

  1. Use a read-only user with readPreference=secondary. Exports are reads; running against a primary contends with write traffic.

    mongoexport \
      --uri="mongodb://export:secret@mongo:27017/shop?readPreference=secondary&authSource=admin" \
      --collection=orders --out=/tmp/orders.json
  2. Filter with --query to keep the export tight. Exporting the entire history when you only need yesterday wastes IO and time.

    mongoexport ... \
      --query='{ "placedAt": { "$gte": { "$date": "2026-06-01T00:00:00Z" }, "$lt": { "$date": "2026-06-02T00:00:00Z" } } }'
  3. Select fields explicitly for CSV. The order in --fields is the column order in the CSV output.

    mongoexport ... \
      --type=csv \
      --fields=_id,customerId,placedAt,amount,status,shipRegion \
      --out=/tmp/orders-20260601.csv
  4. Stream directly to S3 or GCS without intermediate disk.

    mongoexport ... --type=csv --fields=... \
    | gzip -9 \
    | aws s3 cp - s3://exports/shop/orders/$(date -u +%Y/%m/%d).csv.gz
  5. For JSON, use --type=json and emit one document per line. Most data warehouses (BigQuery, Snowflake) ingest newline-delimited JSON directly.

    mongoexport ... --type=json --jsonFormat=relaxed \
    | gzip -9 \
    | gsutil cp - gs://exports/shop/orders/$(date -u +%Y/%m/%d).ndjson.gz
  6. For consistent snapshots, use a session with snapshot read concern.

    mongoexport ... \
      --readPreference=secondary \
      --uri="mongodb://...?readConcernLevel=snapshot"

Operational notes

  • mongoexport is for data movement, not backup. It loses type information that BSON preserves (e.g., 64-bit longs become JSON numbers and may lose precision). For backup, use mongodump.
  • Extended JSON v2 vs relaxed. --jsonFormat=canonical keeps full type information ({"$date": {"$numberLong": "..."}}); --jsonFormat=relaxed is more human-readable and what most downstream tools expect.
  • CSV cells containing commas or quotes are double-quoted with embedded quotes escaped. Standard CSV escaping, but verify the consumer handles it.
  • Field paths with hyphens or special characters need quoting in the shell, otherwise the shell parses them. Wrap the entire --query argument in single quotes.
  • Long-running exports hold a cursor open. If the cursor times out (default 10 minutes of inactivity), the export fails partway. Use --noCursorTimeout for very large datasets and ensure the connection survives.
  • For schema-changing collections, the field set can drift. If documents added during the export contain a field not in --fields, that field is omitted from the CSV (correctly, but possibly silently).

Stack Harbor builds mongoexport-based pipelines for clients feeding analytics warehouses, BI tools, and downstream services from MongoDB — daily incremental exports, point-in-time snapshots for compliance reporting, and ad-hoc exports for data-engineering investigations. We pair these with change-stream-based CDC for low-latency needs and keep both paths available. See /en/services/managed-operations/ for the engagement model and /en/knowledge-base/mongodb-change-streams-realtime/ for the streaming alternative.