When you encounter a problem in your work, you need to take some of the qualifying data out of a collection and process some of the fields one at a line. MongoDB Terminal support directly write JS code, functions, you can also run JS file.
1 first need to set MONGO Terminal Code Editor, do not set the words can only enter a line of code files, can not handle large segment JS logic
After entering the MONGO terminal, enter
f={}
After carriage return, continue to enter:
Edit F
If the related system variables are not set, you will receive the following prompt:
Define EDITOR as a JavaScript string or as an environment variable
We can enter the following statement to set EDITOR:
Editor= "/usr/bin/vim"
This will temporarily set up the Vim editor as a subsequent JS code editor. This is a temporary method that must be set again after you turn off MONGO and use it again. You can try to add editor= "/usr/bin/vim" to the system environment variable, I have not tried for the moment ...
2 Write JS code: After setting up the editor, the terminal input:
Tempfunc = {}
Continue entering after carriage return:
Edit Tempfunc
It will go into the editor environment that I just set up, and here I am the VIM environment. Note: All content entered in Vim will be replaced with the right part of the equal sign in "Tempfunc =". So if you're not just trying to edit a single line of code, it's best to edit it into a function in vim, making sure that the substitution becomes the form of Tempfunc = function () {...}. The full content of my edits in Vim is as follows:
Attention:
Be sure to carefully check the syntax, if you accidentally hit the wrong word, call time is no effect, there is no way to edit again, can only edit again from the beginning!!!
After editing the Wq exit vim, we define a tempfunc function as a whole.
Enter the function call in the terminal:
Tempfunc ()
MONGO will remove all grade<2 data from the entities table and then write back to the database for grade +1.
Note:
1: There is a problem with the UPDATE statement here: The original grade If it is a int32 type, it will become a double type after writing. Including operations such as Using Inc and Dec, the Int32 type of data is rewritten as a double type. With the Numberint function, you can solve
You can change the UPDATE statement to this:
Db.entities.update ({_id:rowdata["_id"}, {$set: {grade:numberint (Newgrade)}}, {multi:false});
2: As far as possible to define a function body, to facilitate the overall call. If you do not want to define a function, you can enter edit{} directly at the beginning, and then delete the default reserved {} In Vim, you can write a line of JS code, and finally exit Vim will be compressed into a line of code, similar to this, and then press ENTER to execute directly:
var cursor = Db.entities.find (); while (Cursor.hasnext ()) {var row = Cursor.next (); Print (row["grade"]);}
Write multiple lines of JavaScript code, functions in a MONGODB terminal environment