MongoDB shell: reading a line from the console

戏子无情 提交于 2019-11-29 06:48:25

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.

  1. 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.
  2. 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!