Q: Why do I see an error when I re-run an IntelliShell script?
A: The most likely cause of this is that you’ve added a variable declaration to your script, a let or var statement.
When you run a script with a declaration the first time, everything will work perfectly. But the second time around the shell will give an error because it thinks it is seeing those variables being declared again. That’s something it won’t allow.
By design, Studio 3T’s IntelliShell reuses the underlying Mongo Shell executable each time you run a script. It’s a design that makes things faster for most use cases.
But if you are writing a more complex Mongo Shell script, then you are going to need to declare variables, first for syntactic correctness and secondly, to suppress the shell’s automatic “print results” behavior.
Restart to Quickly Clear a Re-Run Error
The quick fix for this is simply to Restart the Mongo Shell. There’s a toolbar item for that purpose just above the editor.
If you want to quickly reuse a script without restarting the Mongo Shell, then there is a way to get around the problem. Take this script for example:
db = db.getSiblingDB("Example-Datasets");
var results=db.getCollection("customers").find({}).toArray();
for(r of results) {
print(r.first)
}
Run this query once and it will print out all the first names from the collection (and yes there are easier ways to do that). Re-run it for a second time and you’ll get an IntelliShell error about redeclaring results. Click Restart Mongo Shell and a clean shell will be created and it’ll work when you run it again. But you don’t want to be repeatedly restarting for scripts.
Delete to Stay Neat
There’s a shell command, delete, which can delete parts of objects, which is handy in itself. It can also, though, delete entire variables and any record of their declaration. That means we can tidy up before we run a script. If we just delete the only variable we declare before we start the script…
delete results;
db = db.getSiblingDB("Example-Datasets");
var results=db.getCollection("customers").find({}).toArray();
for(r of results) {
print(r.first)
}
We can now repeatedly run the script with no errors and without restarting the shell. Happy re-running your scripts!