3

I would like to know how to execute a JavaScript file in MongoDB.

This is the simple piece of code present in my JS file:

function loadNames() {
    print("name");
}

From the command prompt I tried to execute the file like this

mongo test.js

but it shows the error:

unexpected identifier

Can anyone explain to me where I'm going wrong?

3 Answers 3

13

I usually run my test queries like this, and it works with your sample code too.

mongo < test.js
Sign up to request clarification or add additional context in comments.

Comments

1

two meothods to achieve this:

1 . use "--eval"

mongo quickstats_db --eval "printjson(db.getCollectionNames())"

2 . execute the js file

mongo quickstats_db print.js

where content of print.js is:

printjson(db.getCollectionNames())

Comments

0

From mongo --help, we got:

$ mongo --help
MongoDB shell version v3.6.2
usage: mongo [options] [db address] [file names (ending in .js)]
db address can be:
  foo                   foo database on local machine
  192.168.0.5/foo       foo database on 192.168.0.5 machine
  192.168.0.5:9999/foo  foo database on 192.168.0.5 machine on port 9999
Options:
  --shell                             run the shell after executing files
  --nodb                              don't connect to mongod on startup - no 
                                      'db address' arg expected
  --norc                              will not run the ".mongorc.js" file on 
                                      start up
  --quiet                             be less chatty
  --port arg                          port to connect to
  --host arg                          server to connect to
  --eval arg                          evaluate javascript
  -h [ --help ]                       show this usage information
  ... ...

and referred mognodb's tutorial/document, we got this script named as my-mongo-script.js:

'use strict';

// @see https://docs.mongodb.com/manual/tutorial/write-scripts-for-the-mongo-shell/

var MONGODB_URI = "mongodb://127.0.0.1:27020/testdb";

var db = connect(MONGODB_URI);

var collections = db.getCollectionNames();

print(collections.join('\n'));

printjson(collections);

so this cmd mongo --nodb my-mongo-script.js will execute the script.

You can add a "--shell" like mongo --nodb --shell my-mongo-script.js to "run the shell after executing files".

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.