thesmart
thesmart

Reputation: 3073

How to require scripts in Mongo Shell CLI

I'd like to be able to import a library of common tools that I use to make working with MongoDB easier. However, I haven't discovered an easy to to import external scripts into the Mongo CLI. Ideally, this would work similar to Node.js require.

How can I get require working in Mongo CLI by default?

Or, is there some other way to solve external library dependencies?

Upvotes: 7

Views: 1938

Answers (1)

Stennie
Stennie

Reputation: 65363

There are several options for loading JavaScript into the mongo shell:

1) Save the JavaScript to .mongorc.js in your home directory.

2) Save the JavaScript to the global mongorc.js file (MongoDB 2.6+) which is evaluated before the .mongorc.js file in your home directory.

3) Use load('filename.js') from within the shell (or within one of the mongorc.js files).

4) Store your JavaScript on the server using the system.js collection and db.loadServerScripts().

For common JavaScript functions, the first option is the most typical approach.

Upvotes: 12

Related Questions