MongoDB shell: reading a line from the console

后端 未结 2 1950
北海茫月
北海茫月 2020-12-17 21:02

Is there a way to read a line from the Mongo shell? readline() is not defined and neither is system.stdin.

I need to do this in interactive

相关标签:
2条回答
  • 2020-12-17 21:21

    Per @Stennie's comment, this is not possible right now.

    0 讨论(0)
  • 2020-12-17 21:30

    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.

    0 讨论(0)
提交回复
热议问题