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