Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to require scripts in Mongo Shell CLI

Tags:

mongodb

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?

like image 747
thesmart Avatar asked Aug 21 '12 20:08

thesmart


People also ask

How do I run a mongo shell script?

Execute a JavaScript file js script in a mongo shell that connects to the test database on the mongod instance accessible via the localhost interface on port 27017 . Alternately, you can specify the mongodb connection parameters inside of the javascript file using the Mongo() constructor.

How use mongo shell in CMD?

To open up the MongoDB shell, run the mongo command from your server prompt. By default, the mongo command opens a shell connected to a locally-installed MongoDB instance running on port 27017 . Try running the mongo command with no additional parameters: mongo.

Can I use JavaScript in MongoDB?

MongoDB supports JavaScript through the official Node. js driver. You can connect your Node. js applications to MongoDB and work with your data.


1 Answers

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.

like image 135
Stennie Avatar answered Sep 29 '22 02:09

Stennie