Import Data in MongoDB using Mongoimport

Here you are going to learn how to import JSON data or CSV file into a collection in MongoDB.

Use mongoimport command to import data into a collection. You should have installed the MongoDB database tools to use the mongoimport command.

To install the database tools, visit Database tools and download the zip file for your platform.

Now, extract and copy all .exe files and paste them to the MongoDB bin folder. On Windows, it is C:\Program Files\MongoDB\Server\<version>\bin folder.

Now, open the terminal or command prompt and navigate to the location where you have the JSON file to import so that you don't need to specify the whole path.

The following is the mongoimport command.

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

Now, execute the following command to import data from D:\MyData\employeesdata.json file to employees collection

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

The above command will import data into the employees collection in the test database. Note that --jsonArray indicates that the data in a file contains in an array.

Import Data from CSV File

Consider that you have D:\employeesdata.csv file which you want to import into new employee collection. Execute the following command to import data from the CSV file.

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

The --fields option indicates the field names to be used for each column in the CSV file. If a file contains the header row that should be used as a field name then use --headerline option instead of --fields. The above command will insert all data into employees collection, as shown below.

test> db.employees.find()
[
  { _id: 2, firstName: 'bill', lastName: 'gates' },
  { _id: 1, firstName: 'steve', lastName: 'jobs' },
  { _id: 3, firstName: 'james', lastName: 'bond' }
]
Want to check how much you know MongoDB?