1

I run the following in MongoDB shell (version 4.2, as reference):

while(true) { db.c.update({_id:1}, {$inc: {n: 1}}) }

I want to break the while loop, but without ending the MongoDB shell. If I use Ctrl+C the loop ends, but also the mongo process (like if I have done exit).

Looking to mongo shell documentation I found Ctrl+G as "abort" but it's not working (it seems to do nothing).

Is possible to do what I'm trying? What the purpose of Ctrl+G?

Thanks!

fgalan
  • 11,732
  • 9
  • 46
  • 89

2 Answers2

2

Not possible. You are confusing aborting the MongoDB operation with JS execution.

Ctrl + G aborts individual CRUD operation, not while(true){...}

Let's see this example:

db.collection.find({$where:"this.foo==1"});print("1");db.collection.find({$where:"this.foo==1"});print("2");
> executing...
> Ctrl + G
> 1
> executing...
> Ctrl + G
> 2
Valijon
  • 12,667
  • 4
  • 34
  • 67
1

We shouldn't confuse the JS execution with aborting the shell.

To abort a JS query within MongoDB shell, take a look at this thread: How do I abort a query in mongo JavaScript shell.

On the programming side, you can use break to cause JS loop interruption, without affecting the shell.

For example, to have just 10 repetitions of your snipper, every 2 seconds, you can do something like this...

var i=1;
while(true) {
    db.c.update({_id:1}, {$inc: {n: 1}});
    if(i>10) {
        break;
    }
    sleep(2000);
    i++;
}

Also, the MongoDB shell supports try/catch blocks, as well as a sleep() method. All you need is there, I believe :-).

idrositis
  • 1,136
  • 10
  • 10