2

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?

5
  • You could combine all js files into one js file. Commented Sep 22, 2020 at 1:49
  • Within mongo shell: You can create an array of the js file names. Then use the load() to run the js scripts in a loop, e.g., for (let file of jsfiles) load(file). Commented Sep 22, 2020 at 3:45
  • From the command line you can specify more than one file, e.g.: mongo localhost/test script1.js script2.js Commented Sep 22, 2020 at 4:02
  • @mhery can you please post the contents of db.users.js? Commented Oct 4, 2020 at 2:12
  • 1
    @user2243747, this file could have any mongo db method. in my project, this file right now just have db.createCollection('users') Commented Oct 4, 2020 at 2:23

1 Answer 1

4

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)
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.