Friday 4 July 2014

Use an External Editor in the mongo Shell

Hi friends, I know the break was little longer. Got stuck with lot of different stuff actually. But better late than never.

I will resume our MongoDB mania with an interesting topic today.

We have been using the mongo shell for the purpose of writing/editing the operations/functions etc. That might be difficult sometime when we have to write a bigger function and execute the same. Think of a situation when you have written down a big function (of 5 lines say) and found that there is a syntax error in line 2, it is very difficult to go back and edit the same through mongo shell.

One option may be write the function in an external .js file and load it into the mongo shell as discussed here.

The other option is also interesting. We can open an external editor (of our choice) from the mongo shell itself and edit some existing function or script.

In mongo shell you can use edit option to edit an existing code/fucntion. The edit command of the shell use the EDITOR variable to open the function in the specified editor.

Open the command prompt and set the EDITOR variable as follows (if it is not set already).

D:\mongodb-win32-x86_64-2008plus-2.4.9\bin>set EDITOR=%windir%\system32\notepad.exe

D:\mongodb-win32-x86_64-2008plus-2.4.9\bin>echo %EDITOR%
C:\Windows\system32\notepad.exe




Now start your mongod in a different command window. Come back to the previous command prompt (where we have set the EDITOR variable) and connect to the mongod using mongo shell.

D:\mongodb-win32-x86_64-2008plus-2.4.9\bin>mongo.exe
MongoDB shell version: 2.4.9
connecting to: test
>


Try writing some new function:

> function myfunc() {}
>


Check the content of the function by tying the function name on the shell:


> myfunc
function myfunc() {}
>


Now we will edit this function in the external editor (notepad in this case). Type the edit command as follows:

> edit myfunc

You will see the function myfunc() will open in a notepad window. 



Now edit the function as per your requirement. See below:




After you complete, save the changes (not save-as) and close the editor window (don't forget to save). You will see the prompt will be back on the mongo shell.

Now to check the content, type the function name on the shell:

> myfunc
function myfunc() {
        print("the function has been edited using an external editor");
}
>


Run the function on the shell as follows:

> myfunc()
the function has been edited using an external editor
>


Cool !!! right. Enjoy using the external editor for your need.



<< Prev                                                                                     Next >>

No comments:

Post a Comment