最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Executing JavaScript file in MongoDB - Stack Overflow

programmeradmin3浏览0评论

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 mand 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?

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 mand 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?

Share Improve this question edited Sep 22, 2017 at 18:01 CommunityBot 11 silver badge asked Nov 24, 2013 at 12:57 user1585111user1585111 1,0196 gold badges19 silver badges35 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 13

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

mongo < test.js

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

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

发布评论

评论列表(0)

  1. 暂无评论