How to terminate a MongoDB shell script earlier?

To terminate a MongoDB shell script earlier, you can use the quit() or quit(1) command. This immediately exits the MongoDB shell and returns control to the operating system command prompt.

Syntax

quit()
quit(1)

Where quit() exits with status code 0 (success), and quit(1) exits with status code 1 (error).

Sample Data

Let us first create a collection with sample documents to demonstrate the quit functionality ?

db.flightInformation.insertMany([
    {"FlightName": "Flight-1", "ArrivalTime": new ISODate("2019-03-12")},
    {"FlightName": "Flight-2", "ArrivalTime": new ISODate("2019-03-31")}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5ca1e341e941bbb0e8bf5639"),
        ObjectId("5ca1e351e941bbb0e8bf563a")
    ]
}

Example: Displaying Data Before Exit

Display all documents and then terminate the shell ?

db.flightInformation.find().pretty();
{
    "_id": ObjectId("5ca1e341e941bbb0e8bf5639"),
    "FlightName": "Flight-1",
    "ArrivalTime": ISODate("2019-03-12T00:00:00Z")
}
{
    "_id": ObjectId("5ca1e351e941bbb0e8bf563a"),
    "FlightName": "Flight-2",
    "ArrivalTime": ISODate("2019-03-31T00:00:00Z")
}

Terminating the Shell

Now terminate the MongoDB shell script ?

quit();
C:\Users\Amit>

Key Points

  • quit() exits with status code 0 (normal termination)
  • quit(1) exits with status code 1 (indicates error condition)
  • Both commands immediately close the MongoDB shell session

Conclusion

Use quit() or quit(1) to immediately terminate a MongoDB shell script. This returns control to the operating system prompt and can be useful for conditional exits in shell scripts.

Updated on: 2026-03-15T00:41:13+05:30

571 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements