Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

วิธีตรวจสอบว่า MongoDB Database มีอยู่จริงหรือไม่

การตรวจสอบว่า MongoDB Database มีอยู่จริงหรือไม่

ใช้ db.getMongo().getDBNames().indexOf("databaseName") เพื่อตรวจสอบว่า Database ชื่อนั้นมีอยู่ใน MongoDB Instance หรือไม่

ไวยากรณ์

db.getMongo().getDBNames().indexOf("yourDatabaseName");

ผลลัพธ์ที่เป็นไปได้

  • Index >= 0 (เช่น 0, 1, 6, ...) : Database มีอยู่จริง ค่าที่ได้คือ Index ใน Array (เริ่มจาก 0)
  • -1 : Database ไม่มีอยู่

กรณีที่ 1: Database มีอยู่ (test)

> db.getMongo().getDBNames().indexOf("test");
6

ตรวจสอบด้วย show dbs

> show dbs;
admin        0.001GB
config       0.000GB
local        0.000GB
sample       0.001GB
sampleDemo   0.000GB
studentSearch 0.000GB
test         0.009GB

สังเกต: "test" อยู่ที่ Index 6 (นับจาก 0: admin=0, config=1, local=2, sample=3, sampleDemo=4, studentSearch=5, test=6) ตรงกับผลลัพธ์ indexOf

กรณีที่ 2: Database ไม่มีอยู่ (education)

> db.getMongo().getDBNames().indexOf("education");
-1

ผลลัพธ์ -1 หมายถึง Database "education" ไม่มีอยู่ใน Instance นี้

คำอธิบายคำสั่ง

  • db.getMongo() : ได้ Mongo connection object
  • .getDBNames() : คืน Array ของชื่อ Database ทั้งหมด
  • .indexOf("name") : หา Index ของชื่อใน Array (คืน -1 ถ้าไม่เจอ)

วิธีอื่นๆ ในการตรวจสอบ Database

1. ใช้ show dbs (Shell Command)

> show dbs;

แสดงรายการ Database พร้อมขนาด (ต้องมีข้อมูลอย่างน้อย 1 Collection จะแสดง)

2. ใช้ ListDatabases Command

> db.adminCommand({ listDatabases: 1 });

คืนข้อมูลละเอียดรวมถึง sizeOnDisk, empty flag

3. ใช้ JavaScript Check

> var dbs = db.getMongo().getDBNames();
> dbs.includes("test");  // true/false (MongoDB 4.4+ / Modern JS)
> dbs.indexOf("test") !== -1;  // ทุก Version

4. พยายาม Switch Database (Implicit Check)

> use test;
switched to db test
> db.stats();
// ถ้า Database ไม่มี จะสร้างใหม่ตอน Insert ข้อมูลครั้งแรก

ข้อสังเกตสำคัญ

💡 Database ใน MongoDB ถูกสร้างแบบ Lazy

  • Database ไม่ถูกสร้างจนกว่าจะมีการ Insert ข้อมูลครั้งแรก
  • use nonExistentDB จะ switch ได้ แต่ show dbs จะไม่แสดง จนกว่าจะมีข้อมูล
  • db.stats() หรือ db.createCollection() จะสร้าง Database จริง

การใช้งานใน Script/Application

function databaseExists(dbName) {
    return db.getMongo().getDBNames().indexOf(dbName) !== -1;
}

// ใช้งาน
if (databaseExists("myApp")) {
    print("Database exists");
} else {
    print("Database does not exist");
}

วิธี indexOf เป็นวิธีที่ตรงไปตรงมาและทำงานได้ในทุก Version ของ Mongo Shell