How to load multiple js files to database using mongo shell?

Viewed 631

I have several js files with collections creations and seeds. I load data from one of them using, for example,

mongo <host>:<port>/<database> -u <user> -p <password> < db.users.js

However, now I have several files, and I wish I could load all of them to mongo using one command. Hopefully, with mongo shell.

Is there any way I can do it?

1 Answers

There are different ways to load (run) these files. I have two js files script1.js and script2.js, for example.

From OS command line specify all the files:

mongo localhost/testdb script1.js script2.js

Or, create one js file and include all the scripts. For example, create a script_combined.js with the following:

load("script1.js")
load("script2.js")

Run as:

mongo localhost/testdb script_combined.js

Alternative way to run multiple scripts from within mongo shell:

> const script_files = [ "script1.js", "script2.js" ]
> for (let file of script_files) {
      load(file)
  }
Related