user1585111
user1585111

Reputation: 1019

Executing JavaScript file in MongoDB

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?

Upvotes: 3

Views: 12875

Answers (3)

Fisher
Fisher

Reputation: 379

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".

Upvotes: 0

keypoint
keypoint

Reputation: 2318

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())

Upvotes: 1

David Filipidisz
David Filipidisz

Reputation: 141

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

mongo < test.js

Upvotes: 13

Related Questions