|
The MongoDB shell is not just an interactive shell, it can also be scripted using JS files. In addition to specifying a Javascript file (*.js) you can also use --eval with a snippet of JS. Using the shell this way allows for tasks to be performed without the need for any additional drivers or language support; it can be used in cron, or automated administrative tasks. Please be aware there are data format issues in javascript so you should be careful how much you do in Javascript. Common uses for the scripted shell includes:
Running a Script./mongo server:27017/dbname --quiet my_commands.js The syntax stems from the interactive shell. This command will execute the my_commands.js as if it had been entered into the shell directly, with some exceptions.
--quietThis option will remove the header printed at the top when you run the shell normally: $ mongo MongoDB shell version: 2.1.0 connecting to: test > ^C bye $ mongo --quiet > ^C --evalIn addition to using a full Javascript file you can also pass in a Javascript fragment: bash-3.2$ ./mongo test --eval "printjson(db.getCollectionNames())" MongoDB shell version: 1.8.0 connecting to: test [ "system.indexes", "t1", "t2", "test.fam", "test1", "test11", "testBinary", "testarray" ] Differences between scripted and interactivePrintingWhen using the shell interactively, the shell will print returned values and format where possible. This is done as a general convenience from within the shell. However, when building a script, the printing needs to be defined explicitly. There are two functions commonly used for this:
Example: print JSON for the first 10 objects from a find db.foo.find({x:1}).forEach(printjson)
use dbnameThis command does not work in scripted mode. Instead you will need to explicitly define the database in the connection (/dbname in the example above). Alternately, you can also create a connection within the script: > help connect // for more help > var x = new Mongo('host[:port]'); > var mydb = x.getDB('mydb'); > // or > var mydb = connect('host[:port]/mydb'); itThe iterator command it does not work outside of the interactive scripting environment. getLastErrorWhen running an update/insert command from the shell, the shell automatically awaits a reply (i.e. runs a get last error). The same is not true when running from a script file. To wait for the status of an operation (such as a write), run the getLastError function after update/insert. db.getLastErrorObj()
// or
db.getLastError()
|

PLEASE POST QUESTIONS IN THE USER GROUPS FORUM. Post non-question comments and helpful hints here.
blog comments powered by Disqus