0
0
MongodbHow-ToBeginner · 3 min read

How to Import JSON to MongoDB: Simple Steps

To import a JSON file into MongoDB, use the mongoimport command-line tool with the --jsonArray option if your file contains an array of JSON documents. The basic syntax is mongoimport --db yourDB --collection yourCollection --file yourFile.json --jsonArray.
📐

Syntax

The mongoimport command imports JSON data into a MongoDB database. Key parts include:

  • --db: The target database name.
  • --collection: The collection to import data into.
  • --file: The path to your JSON file.
  • --jsonArray: Use this if your JSON file contains an array of documents.
bash
mongoimport --db <database_name> --collection <collection_name> --file <path_to_json_file> --jsonArray
💻

Example

This example imports a JSON file named data.json containing an array of documents into the users collection of the testdb database.

bash
mongoimport --db testdb --collection users --file data.json --jsonArray
Output
2024-06-01T12:00:00.000+0000 connected to: mongodb://localhost/ 2024-06-01T12:00:00.100+0000 imported 3 documents
⚠️

Common Pitfalls

Common mistakes when importing JSON to MongoDB include:

  • Not using --jsonArray when the JSON file contains an array, causing import failure.
  • Incorrect file path or file name.
  • Trying to import JSON lines format without specifying the correct format.
  • Importing into a non-existent database or collection without realizing MongoDB creates them automatically.
bash
Wrong (missing --jsonArray):
mongoimport --db testdb --collection users --file data.json

Right:
mongoimport --db testdb --collection users --file data.json --jsonArray
📊

Quick Reference

OptionDescription
--db Specify the database name
--collection Specify the collection name
--file Path to the JSON file to import
--jsonArrayUse if JSON file contains an array of documents
--dropDrop the collection before importing (optional)

Key Takeaways

Use the mongoimport tool with --jsonArray to import JSON arrays correctly.
Always specify the target database and collection with --db and --collection.
Check your JSON file format and path before importing.
MongoDB creates the database and collection if they do not exist.
Use --drop to clear existing data before import if needed.