Load JSON Files to a MongoDB Database Using Mongoimport on Linux or Windows

Make sure you are out of the mongo shell before you start. Mongoimport is a stand-alone utility that is not part of the shell.

Liunx

Import a single file

mongoimport -d databaseName -c collectionName --file /home/myFiles/myJsonFile.json -u username -p password --authenticationDatabase admin

Import all files from a folder

ls *.json | xargs -I filename 
mongoimport -d targetDatabase -c targetCollection --file /home/myFiles/myJsonFile.json-u username -p password --authenticationDatabase admin

Here is another way to import all files using a shell script.

First create a shell file

vim /targetdirectory/filename.sh


Copy the following in to the file and save. Make sure the file type is sh:

for f in *.json
do
echo "Processing $f file...";
mongoimport --file $f -d testimport -c testing -u $1 -p $2 --authenticationDatabase admin && mv $f $f.processed;
done

Make the file an executable

chmod +x filename.sh

We are now ready to execute the shell script. In the file we created we set 2 parameters for username and password. This allows us to use security without storing the credentials in the file itself. Cal the file name and pass in the username and password to import files.

./filename.sh username password

Windows

When using the Windows CLI to work with Mongoimpot, make sure you are running these commands from the directory where mongoimport resides. This can usually be found in the bin folder. You could also setup environment variables for this.

Import a single file

mongoimport --db databaseName --collection collectionName --file C:\MongoDB\myFile.json

For all files in a folder

C:\Users\bhettrick> for %i in (C:\JSONDocuments\tmp\*) do mongoimport --file %i --type json --db MyDB --collection teststore


Windows Batch version:

@echo off
for %%f in (*.json) do (
"mongoimport.exe" --jsonArray --db MyDB --collection collectioname --file %%~nf.json
)