Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to terminate earlier a MongoDb shell script?

Writing:

if (...) {
    return;
}

in a MongoDb shell script will complain: SyntaxError: return not in function

I have also tried the exit mongo console command:

if (...) {
    exit;
}

but you get the error: ReferenceError: exit is not defined

How can one earlier terminate the execution in the js script file?

like image 433
4 revs, 2 users 76% Avatar asked Jul 24 '13 12:07

4 revs, 2 users 76%


People also ask

How do I stop MongoDB?

One liners to start or stop mongodb service using command line; To start the service use: NET START MONGODB. To stop the service use: NET STOP MONGODB.

How do I close MongoDB on terminal?

Manually stop the MongoDB service by using one of the following methods: Run the /etc/init. d/mongodnetbrain stop command at the command line. Run the service mongodnetbrain stop command at the command line.


2 Answers

In mongodb you can use the quit() function as documented here. While it's not documented well, I did a quick test and can return a non zero exit code by doing quit(1) which will exit w/ status 1.

like image 159
NG. Avatar answered Sep 28 '22 07:09

NG.


I have used the following solution:

(function(){

    // now you can use the return keyword anywhere:
    if (/* some condition */) {
        print("This is an error condition");
        return;
    }

})();

I know that terminating the script this way will not make mongo return an error code different than 0 (as the accepted solution does).

like image 21
4 revs, 2 users 76% Avatar answered Sep 28 '22 08:09

4 revs, 2 users 76%