MongoDB shell: reading a line from the console
Per @Stennie's comment, this is not possible right now.
Officially, this is not possible in Mongo shell.
Unofficially, yes it is possible. There is one small hack you can use to read user input.
Mongo shell among many undocumented functions, contains one function named passwordPrompt
which can be used to read user input.
Just, there are some limitations with this hack you must be aware of.
- This function, once called, prints string
Enter password:
to console, and has no option to change this prompt. Since this function is native (non js) it is not possible to redefine it to remove prompt. - This function will not show you what you type as you type it (makes sense since mongo shell uses it internally for entering user passwords). You will have to type in your input blindly.
But if you do not mind having "Enter password:" prompt appearing each time you wish to get user input, and not seeing what you type, then this should work.
Here is one example. You can run it in both interactive mode or write it inside .js file:
user_input = passwordPrompt();
print("user inputed: " + user_input);
If you run it and type "hack nation", output from this will be:
Enter password:
user inputed: hack nation
Also, Mongo shell allows you to run OS commands from shell itself, what allows you to handle user input using non-mongo and non-javascript utilities. For example, I have created programs for mongo shell which use windows powershell and .net framework to make graphic user interface and interact with user using gui, and return user input back to Mongo shell. I prefer this over passwordPrompt
.
There are quite a few undocumented functions in Mongo shell you can use to do some more advanced things, such as getting user input, file system I/O functions, etc.