Q: I’m using Intellishell in Studio 3T to run MongoDB shell scripts. I’m using the output from the Raw Shell Output tab but I notice that there’s unexpected and apparently random output in there. Can I stop this so I don’t have to manually edit it out?
Welcome to the latest Studio 3T Ask Manatees Anything – #Studio3T_AMA. Want to know how to use Studio 3T to make your MongoDB life better? Just tweet and use #Studio3T_AMA or email [email protected].
A: The answer is yes, that output isn’t random and it’s worth knowing why it happens.
Let’s step back and look at what causes the problem. Shells like Mongo Shell, which sits underneath IntelliShell, are what’s called REPLs. That stands for Read, Evaluate, Print, Loop. So the shell reads your command, evaluates your command, prints the result and loops around. It’s the print part that’s causing the problem here.
The shell prints whatever the last command evaluated. So:
> a=5
5
> a=a+10
15
> print(a)
15
The first line setting `a` evaluates `a` as 5 so the shell prints 5. Then, when we do a calculation, that calculation evaluates `a` as 15 so the shell prints 15. It’s handy when we are interacting with a shell at the keyboard, but when we are running a script and want clean output, it is much less useful.
What you need is something that evaluates to nothing, so nothing gets printed. That’s where `var` comes in. The var statement declares a variable is in scope for the current context. And that’s an action that has no output. An added bonus is that multiple definitions of a var variable don’t generate an error (unlike say let or const). So we can use it like this:
> var a=5
> var a=a+10
> print(a)
15
No stray output, only output when we want it. Now this also works for defining anonymous functions as well:
> b=function(x){return x*2}
function(x){return x*2}
> b(2)
4
This is not what we want; our functions should not be getting printed out, but that’s what it evaluates to. But with var, it goes quiet:
> var b=function(x){return x*2}
> b(2)
4
And defining a function with a var doesn’t stop the function itself evaluating and being printed; just remember to wrap things in a var when you don’t want them to echo. Where it’s something more complex, like overriding a prototype method, you can always try the formulation:
> var nooutput=( Array.prototype.print=function(){ print("No Array Printing") })
> [].print()
No Array Printing
>
So there we have it, a quick way of suppressing unexpected output in MongoDB shell scripts.
Don’t forget though that this is only for the raw shell output. In Studio 3T’s IntelliShell, you can always enable Query Assist to automatically see results from your shell queries turned into tables, trees and JSON views.
Download Studio 3T and try IntelliShell today.