Use of the MongoDB Shell JS (ii)
The MongoDB shell is not only an interactive shell, but also can be accessed using a JS script.
Advantages and disadvantages of using JS script to interact
(1) No driver or language support is required;
(2) To facilitate Cron or manager scheduled tasks;
(3) Note: The problem is still the data format;
JS scripts are typically used to perform the following tasks
(1) Backup;
(2) dispatching Map-reduce command;
(3) Offline reporting, offline tasks;
(4) Regular tasks of the Administrator;
How to run a JS script
./mongo 127.0.0.1:3003/test–quiet Test.js
Description
(1)./mongo
MONGO client-_-;
(2) 127.0.0.1:3003/test
The ip,port of the server, and the database that needs to be connected;
(3) –quiet
Omit some header information
(4) Test.js
The script to be run, the content is:
Db.test.find (). ForEach (Printjson);
You can also use the –eval parameter
./mongo 127.0.0.1:3003/test–eval "Db.test.find (). ForEach (Printjson);
The –eval parameter is followed directly by a JS statement.
A few other notes
(1) Usually two methods are used to print the obtained results:
Print () = Normal JS
Printjson () = format JSON print, print out the format will be beautiful many
(2) The iterator (iterator command) will fail in the script operation
(3) How to know if the INSERT, delete, update and other operations are successful, please use:
Db.getlasterrorobj ()
Or
Db.getlasterror ()
(4) JS Shell related introduction See:
Https://developer.mozilla.org/En/SpiderMonkey/Introduction_to_the_JavaScript_shell
http://www.habadog.com/2011/08/09/mongodb-shell-use-js/
Use of the MongoDB Shell JS (ii)