0
0
MongodbHow-ToBeginner · 3 min read

How to Use mongoimport: Import Data into MongoDB Easily

Use the mongoimport command-line tool to import data files like JSON, CSV, or TSV into a MongoDB database. Specify the target database, collection, and file format with options like --db, --collection, and --file.
📐

Syntax

The basic syntax of mongoimport includes specifying the database, collection, and input file. You can also set the file type and connection details.

  • --db: The database name to import data into.
  • --collection: The collection name where data will be inserted.
  • --file: The path to the data file to import.
  • --type: The file format, such as json, csv, or tsv. Defaults to JSON.
  • --headerline: For CSV/TSV files, uses the first line as field names.
  • --drop: Drops the collection before importing data.
bash
mongoimport --db <database> --collection <collection> --file <filename> --type <filetype> [--headerline] [--drop]
💻

Example

This example imports a JSON file named products.json into the store database and items collection.

bash
mongoimport --db store --collection items --file products.json --jsonArray
Output
2024-06-01T12:00:00.000+0000 connected to: mongodb://localhost/ 2024-06-01T12:00:00.100+0000 imported 5 documents
⚠️

Common Pitfalls

Common mistakes include:

  • Not specifying --jsonArray when importing a JSON array file, causing import failure.
  • For CSV/TSV files, forgetting --headerline to use the first row as field names.
  • Not having MongoDB server running or incorrect connection parameters.
  • Importing into the wrong database or collection due to typos.
bash
Wrong:
mongoimport --db store --collection items --file products.json

Right:
mongoimport --db store --collection items --file products.json --jsonArray
📊

Quick Reference

OptionDescription
--db Target database name
--collection Target collection name
--file Path to the input data file
--type Input file format, default is json
--jsonArrayUse if JSON file contains an array of documents
--headerlineUse first line as field names for CSV/TSV
--dropDrop collection before importing data

Key Takeaways

Always specify the database and collection with --db and --collection.
Use --jsonArray when importing JSON files containing arrays.
For CSV/TSV files, include --headerline to use the first row as field names.
Ensure MongoDB server is running before importing data.
Use --drop to clear the collection before import if needed.