1
votes

I can run mongoimport from the commandline and get it to import a file if I hardcode the file name. mongoimport --host HOSTNAMEHERE --collection TESTColectionName --db DBNAME --file C:\FileFolder1\129871.json --jsonArray

The above works great but I have a folder with hundreds of.json files (that I do not know the names of). How can I iterate through all the files in the directory and import them into a mongodb?

I have written a few .js files to run mongo commands (find data, display data, print out the data, etc). Is there anyway I can iterate and run imports from here (I know mongoimport is a separate .exe from the mongo shell itself).

Let me know, Thank You

1
Why dont you write a shell script or batch file ? or you could write a small script using node and using 'fs' to iterate through files and excute shell command. - Venkat Reddy
Sorry if that was not clear, but that is what I was looking to do is write a shell script. - Brad

1 Answers

1
votes

A sample shell script to iterate ( Unix based )

ls -1 *.json | sed 's/.json$//' | while read col; do 
mongoimport -d db_name -c $col < $col.json; 
done

windows based HINT

This lists all the files (and only the files) in the current directory:

for /r %i in (*) do echo %i

Also if you run that command in a batch file you need to double the % signs.

for /r %%i in (*) do echo %%i