Streamlining Data Import into MongoDB with mongoimport

Effortlessly migrate your JSON or CSV data into MongoDB collections using the mongoimport command. This guide provides step-by-step instructions, including installation guidance, for seamless data import. Discover how to leverage mongoimport to populate your MongoDB databases and streamline your development workflow.



Import Data in MongoDB using mongoimport

Learn how to import JSON or CSV data into a MongoDB collection using the mongoimport command. Ensure you have installed MongoDB database tools before using this command.

To install the database tools, visit Database tools and download the zip file for your platform. Extract and copy all .exe files to the MongoDB bin folder, usually located at C:\Program Files\MongoDB\Server\\bin on Windows.

Importing JSON Data

Open the terminal or command prompt and navigate to the directory containing your JSON file. Use the following command to import data:

Syntax

mongoimport --db database_name --collection collection_name ^
            --authenticationDatabase admin --username  --password  ^
            --file file_path
        

Example: Import data from D:\MyData\employeesdata.json into the employees collection of the test database:

Example: Import JSON Data

D:\MyData> mongoimport --db test --collection employees --file employeesdata.json --jsonArray
        

The --jsonArray flag indicates that the data in the file is in an array format.

Importing CSV Data

To import data from a CSV file, use the following command:

Syntax

mongoimport --db database_name --collection collection_name --type csv --file file_path --fields field1,field2,field3
        

Example: Import data from D:\employeesdata.csv into the employeesdata collection:

Example: Import CSV Data

D:\MyData> mongoimport --db test --collection employeesdata --type csv --file employees.csv --fields _id,firstName,lastName
        

The --fields option specifies the field names for each column. If the CSV file has a header row that should be used as field names, use the --headerline option instead of --fields.

Verify the Imported Data

To check the imported data, use the find() method in the MongoDB shell:

Verify Data

test> db.employees.find()
[
  { _id: 2, firstName: 'bill', lastName: 'gates' },
  { _id: 1, firstName: 'steve', lastName: 'jobs' },
  { _id: 3, firstName: 'james', lastName: 'bond' }
]
        

Both methods will create the collection if it does not already exist.