0Pricing
MongoDB Academy · 课时

mongoimport:加载 JSON 和 CSV 文件

您将使用 mongoimport 和各种模式标志,将 JSON 和 CSV 数据文件导入集合。

mongoimport:加载 JSON 和 CSV 文件 是 CoddyKit 上的免费 MongoDB Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 MongoDB Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 MongoDB Academy 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

What Is mongoimport?

mongoimport is a command-line tool bundled with the MongoDB Database Tools package. It loads data from JSON, JSONL (JSON Lines / newline-delimited JSON), and CSV files directly into a MongoDB collection. It is the standard way to seed a collection with initial data, migrate from another database, or bulk-load a data export from a third-party system.

Basic JSON Import

The simplest mongoimport command specifies the connection string, database, collection, and input file. By default it expects a JSON array of objects ([{...},{...}]). The --jsonArray flag is required when importing a file that contains a JSON array; omit it for JSONL (one document per line) format.

# Import a JSON array file into the 'products' collection
mongoimport \
  --uri 'mongodb://localhost:27017/myapp' \
  --collection products \
  --file products.json \
  --jsonArray

# Output:
# 2024-01-01T12:00:00.000+0000  connected to: mongodb://localhost:27017
# 2024-01-01T12:00:00.100+0000  100 document(s) imported successfully

JSONL Format: One Document Per Line

JSONL (also called ndjson) stores one JSON document per line with no outer array wrapper. This format is preferred for large files because it can be streamed and processed line-by-line without loading the entire file into memory. mongoimport handles JSONL by default when you omit --jsonArray.

# products.ndjson — one document per line:
# {"name":"Widget","price":9.99}
# {"name":"Gadget","price":19.99}
# {"name":"Donut","price":1.99}

# Import JSONL file (no --jsonArray flag)
mongoimport \
  --uri 'mongodb://localhost:27017/myapp' \
  --collection products \
  --file products.ndjson

Importing CSV Files

For CSV imports, specify --type csv and provide column headers. If the CSV file has a header row, use --headerline to read column names from the first row. If the file has no header row, list the column names with --fields. All CSV values are imported as strings by default—use --columnsHaveTypes to declare types.

# CSV with header row:
# name,price,category
# Widget,9.99,tools
# Gadget,19.99,electronics

mongoimport \
  --uri 'mongodb://localhost:27017/myapp' \
  --collection products \
  --type csv \
  --headerline \
  --file products.csv

Specifying Field Names for Headerless CSV

When the CSV file lacks a header row, list the field names with the --fields flag. The order of names in --fields must match the column order in the CSV. This approach is common when importing exports from legacy systems that don't include headers.

# CSV without header:
# Widget,9.99,tools
# Gadget,19.99,electronics

mongoimport \
  --uri 'mongodb://localhost:27017/myapp' \
  --collection products \
  --type csv \
  --fields 'name,price,category' \
  --file products_no_header.csv

Import Modes: insert, upsert, merge

mongoimport supports three write modes controlled by --mode:

  • insert (default): insert all documents; fails on duplicate _id
  • upsert: insert if not exists, replace if exists (matching on --upsertFields)
  • merge: insert if not exists, merge fields if exists without replacing the whole document
Use upsert for idempotent re-imports.

# Upsert mode — safe to run multiple times
mongoimport \
  --uri 'mongodb://localhost:27017/myapp' \
  --collection products \
  --file products.json \
  --jsonArray \
  --mode upsert \
  --upsertFields 'sku'  # match on the 'sku' field

The --drop Flag: Replace Collection Contents

The --drop flag drops the target collection before importing. This gives you a clean slate on each import, useful for seeding a development environment where you want to reset data to a known state. Do not use --drop in production if the collection holds data that should not be wiped.

# Drop the products collection and reimport from scratch
mongoimport \
  --uri 'mongodb://localhost:27017/myapp' \
  --collection products \
  --file products.json \
  --jsonArray \
  --drop  # drops collection before importing

Importing Into MongoDB Atlas

To import into a MongoDB Atlas cluster, use the full Atlas connection string (SRV format) in the --uri flag. Atlas requires TLS—the SRV URI automatically enables it. You will need your Atlas username and password in the URI or passed via environment variables to avoid storing credentials in shell history.

# Import into Atlas cluster
MONGO_URI='mongodb+srv://username:password@cluster0.abc.mongodb.net/myapp'

mongoimport \
  --uri "$MONGO_URI" \
  --collection products \
  --file products.json \
  --jsonArray

Handling Import Errors

mongoimport continues on non-fatal errors (like duplicate key violations on individual documents) by default and logs a count of failed documents at the end. Use --stopOnError to halt the import on the first error—useful when you need all-or-nothing import semantics. Check the exit code and error count in scripts to detect partial imports.

# Stop the entire import if any document fails
mongoimport \
  --uri 'mongodb://localhost:27017/myapp' \
  --collection products \
  --file products.json \
  --jsonArray \
  --stopOnError

# Check exit code in a script
if [ $? -ne 0 ]; then
  echo 'Import failed!'
  exit 1
fi

Checking mongoimport Version and Installation

mongoimport is part of the MongoDB Database Tools package, which is installed separately from mongod. Verify it is installed with mongoimport --version. On Atlas clusters you can also use the Atlas UI's Data Import feature for small files, or Atlas Data Federation for larger data lake imports. Always match the tools version to your server version to avoid compatibility issues.

# Verify installation
mongoimport --version
# mongodb-database-tools version: 100.9.0
# git version: ...
# Go version: ...

# Install on macOS with Homebrew
# brew install mongodb/brew/mongodb-database-tools

Import Performance Tips

For large imports (millions of documents), these settings significantly improve throughput: (1) Use --numInsertionWorkers to parallelise insertions (default 1, try 4 for bulk loads); (2) Drop indexes before import and rebuild them after—index maintenance during bulk insert is expensive; (3) Use JSONL format instead of a large JSON array to enable streaming; (4) Import from a host close to the MongoDB server to minimise network latency.

# High-throughput bulk import with 4 parallel workers
mongoimport \
  --uri 'mongodb://localhost:27017/myapp' \
  --collection events \
  --file events.ndjson \
  --numInsertionWorkers 4

Quick Check

Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.

Lesson Recap

In this lesson you learned: mongoimport loads JSON, JSONL, and CSV files into a collection via the command line, --mode upsert makes imports idempotent using a specified match field, and --numInsertionWorkers and dropping indexes before bulk imports improve performance. Next up we explore mongoexport for dumping collection data to files.

常见问题解答

「mongoimport:加载 JSON 和 CSV 文件」课时是免费的吗?

是的 — 「mongoimport:加载 JSON 和 CSV 文件」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 MongoDB Academy 课程的其余内容,请升级到 CoddyKit PRO。 MongoDB Academy 课程共包含 4 节课。

「mongoimport:加载 JSON 和 CSV 文件」这节课中我会学到什么?

您将使用 mongoimport 和各种模式标志,将 JSON 和 CSV 数据文件导入集合。 你通过在浏览器中直接运行的动手代码来练习 MongoDB Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 MongoDB Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 MongoDB Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「mongoimport:加载 JSON 和 CSV 文件」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 MongoDB Academy 课中编写并运行代码吗?

能。每节 MongoDB Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. mongoimport:加载 JSON 和 CSV 文件
  2. mongoexport:将集合导出到文件
  3. 使用 mongodump 和 mongorestore 完成完整备份
  4. 使用 Node.js 脚本填充数据
← 返回 MongoDB Academy