0 0
Read Time:1 Minute, 48 Second

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 &lt;user&gt; --password &lt;password&gt; ^
            --file file_path     

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

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

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.

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

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&gt; db.employees.find()
[
  { _id: 2, firstName: 'bill', lastName: 'gates' },
  { _id: 1, firstName: 'steve', lastName: 'jobs' },
  { _id: 3, firstName: 'james', lastName: 'bond' }
]
Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %

Average Rating

5 Star
0%
4 Star
0%
3 Star
0%
2 Star
0%
1 Star
0%

Leave a Comment

Verified by MonsterInsights