Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Cách thoát sớm (terminate) script MongoDB Shell

Giới thiệu

Để kết thúc sớm một script MongoDB shell đang chạy, bạn sử dụng hàm quit() hoặc exit(). Điều này hữu ích khi viết script có điều kiện dừng sớm.

Cú pháp

quit()      // Thoát với exit code 0 (thành công)
quit(1)     // Thoát với exit code 1 (lỗi)
exit()      // Alias của quit()
exit(0)     // Thoát thành công
exit(1)     // Thoát lỗi

Ví dụ minh họa

1. Tạo collection test

> db.thongTinChuyenBay.insertOne({ "TenChuyenBay": "Flight-1", "GioDen": new ISODate("2019-03-12") });
{ "acknowledged" : true, "insertedId" : ObjectId("5ca1e341e941bbb0e8bf5639") }
> db.thongTinChuyenBay.insertOne({ "TenChuyenBay": "Flight-2", "GioDen": new ISODate("2019-03-31") });
{ "acknowledged" : true, "insertedId" : ObjectId("5ca1e351e941bbb0e8bf563a") }

2. Gọi quit() trong shell

> quit();

3. Kết quả - Thoát về system shell

C:\Users\Amit>

Sử dụng trong file script (.js)

File: check_and_exit.js

// Kết nối database
use myDatabase;

// Kiểm tra điều kiện
var count = db.importantCollection.countDocuments();
if (count === 0) {
    print("ERROR: Collection rỗng, thoát script");
    quit(1); // Exit code 1 = lỗi
}

// Tiếp tục xử lý...
print("Collection có " + count + " documents, tiếp tục...");

// Logic xử lý ở đây
db.importantCollection.updateMany({}, { $set: { processed: true } });

print("Hoàn tất xử lý");
quit(0); // Thoát thành công (tùy chọn, script sẽ tự thoát ở cuối)

Chạy script

mongo check_and_exit.js

Kiểm tra exit code trong bash

mongo check_and_exit.js
EXIT_CODE=$?
if [ $EXIT_CODE -ne 0 ]; then
    echo "Script thất bại với exit code: $EXIT_CODE"
    # Gửi alert, rollback, etc.
else
    echo "Script thành công"
fi

Các hàm liên quan

HàmMô tả
quit()Thoát shell ngay lập tức
exit()Alias của quit()
sleep(ms)Tạm dừng ms milli-giây (hữu ích trong loop)
print()In ra stdout
printjson()In JSON format đẹp

Lưu ý

  • quit() chỉ hoạt động trong **mongo shell interactive** hoặc **script .js chạy bằng mongo**
  • Trong MongoDB driver (Node.js, Python...), dùng process.exit() hoặc exception handling
  • Không dùng quit() trong aggregation pipeline hoặc server-side JavaScript (stored procedures)
  • Exit code 0 = success, non-zero = error (chuẩn Unix)

Pattern thường dùng: Early return trong function

function processData() {
    var config = db.config.findOne({ active: true });
    if (!config) {
        print("Không tìm thấy config active");
        return; // Chỉ thoát function, không thoát shell
    }
    
    // Xử lý...
    return result;
}

// Gọi function
var result = processData();
if (!result) {
    quit(1); // Thoát shell nếu function thất bại
}