Making Mongodb Shell scripts getting started
In this post on mongodb, I will be writing about making mongodb shell scripts. These are scripts that can be called from the mongodb shell with the load command, or directly from the main os command line interface my calling mongodb and then passing the path of the js file. These scripts can be used to work with any of the database methods in the mongo shell such as db.getName.
1 - what to know
This is a post on mongodb shell scripts. It is not a getting stared post on mongodb, javaScript, node.js or any other topics that you should know at least a thing or two about before hand in order to get anything of value from these posts.
2 - writing a hello world mongodb shell script
Start by making a folder that will be used to store the shell scripts. If these scripts will be closely tied to a particular project then I might want to call the folder something like mongo_shell or something to that effect in the root path of a project folder.
|
|
After making a new folder to store shell scripts in I then create a file called helloworld.js that looks like this:
|
|
2.1 - running the helloworld.js mongodb shell script from the command line
When that is done I can then call the script from the command line, assuming that the current working directory is the same as where the script is located, this will call the script.
|
|
2.2 running the helloworld.js mongodb shell script from the mongo shell using the load command.
Although most of the time I would want to just run the script from the command line directly, when working withing the mongodb shell scripts can be called from within these using the load command.
|
|
3 - An example the prints some info about a database
So a script can be used to do anything that would be done manually in the mongoShell. Including using methods that get the name of the current database that is being used, and a list of the collection names.
So I could make a script called connect_users.js that connects to and displays some information about a database called ‘mongoose_users’.
|
|
Works like a charm
4 - conclusion
So this was just a quick getting stared post on theses kinds of scripts. I might write more posts on this in the future as my content on mongodb continues to grow.