Skip to content
Latchkey

mongoimport: Load Fixture Data into MongoDB in CI

mongoimport reads a JSON, CSV, or TSV file and inserts each record into a MongoDB collection.

For seeding a test database from a fixture file, mongoimport is faster and simpler than scripting inserts. It ships in the MongoDB Database Tools, separate from mongosh.

What it does

mongoimport reads structured data from a file (or stdin) and writes it to a collection. It handles a single JSON object per line by default, a JSON array with --jsonArray, and delimited files with --type csv|tsv plus --headerline or --fields.

Common usage

Terminal
mongoimport --uri "mongodb://localhost:27017/app" \
  --collection users --file users.json --jsonArray --drop
# CSV with a header row, into a named db/collection
mongoimport --db app --collection items \
  --type csv --headerline --file items.csv

Options

FlagWhat it does
--uri <uri>Connection string (or use --db/--collection/--host)
--collection <name>Target collection
--file <path>Input file (defaults to stdin)
--jsonArrayTreat the input as a single JSON array of documents
--type csv|tsv|jsonInput format
--headerlineUse the first CSV/TSV row as field names
--dropDrop the collection before importing
--mode insert|upsert|mergeHow to handle existing documents

In CI

Use --drop to make seeding idempotent so reruns start from a clean collection. mongoimport is part of the mongodb-database-tools package and is not bundled with the server image; install it in the job if the base image lacks it. Do not pass --jsonArray for newline-delimited JSON, and do not omit it for a real JSON array.

Common errors in CI

"Failed: cannot decode array into a ..." or "invalid character" usually means the file is a JSON array but you forgot --jsonArray (or the reverse). "mongoimport: command not found" means the database tools are not installed. "Failed: error connecting ... connection() : ECONNREFUSED" means the server is not ready; gate the import on a ping loop.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →