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

ค้นหา Collection ที่ชื่อตรง Pattern (Like '%2015%') ใน MongoDB

ใช้ db.getCollectionNames() ร่วมกับ JavaScript Array.filter() และ Regular Expression เพื่อกรองชื่อคอลเลกชันที่ตรง Pattern

สร้างคอลเลกชันทดสอบ (ขึ้นต้นด้วยปี)

> use web;
switched to db web
> db.createCollection("2015-myCollection");
{ "ok": 1 }
> db.createCollection("2019-employeeCollection");
{ "ok": 1 }
> db.createCollection("2015-yourCollection");
{ "ok": 1 }

แสดงคอลเลกชันทั้งหมด

> show collections;

ผลลัพธ์:

2015-myCollection
2015-yourCollection
2019-employeeCollection
applyConditionDemo
check
creatingAliasDemo
emp_info
emptyCollection
removeNullDemo

Query: หาคอลเลกชันที่ชื่อขึ้นต้นด้วย "2015-" (Like '2015-%')

> db.getCollectionNames().filter(function (v) { return /^2015\-/.test(v); })

ผลลัพธ์:

["2015-myCollection", "2015-yourCollection"]

Query: หาคอลเลกชันที่ชื่อขึ้นต้นด้วย "2019-"

> db.getCollectionNames().filter(function (v) { return /^2019\-/.test(v); })

ผลลัพธ์:

["2019-employeeCollection"]

Regular Expression Patterns ที่ใช้บ่อย

Patternความหมายตัวอย่าง Match
/^2015\-/ขึ้นต้นด้วย 2015-2015-abc, 2015-data
/2015/มี 2015 อยู่ที่ไหนก็ได้abc2015, 2015data, my2015col
/2015$/ลงท้ายด้วย 2015col2015, data_2015
/^20(1[5-9]|2[0-9])-/ปี 2015-20292015-, 2020-, 2029-
/^(2015|2019)-/ขึ้นต้น 2015- หรือ 2019-2015-a, 2019-b

ฟังก์ชันช่วยจำ (Helper Function)

// สร้าง Function ไว้ใช้สะดวก
function findCollections(pattern) {
  return db.getCollectionNames().filter(function(name) {
    return new RegExp(pattern).test(name);
  });
}

// ใช้งาน
findCollections("^2015-");
findCollections("2015");
findCollections("^temp_");

หมายเหตุ

  • รันได้เฉพาะใน MongoDB Shell (JavaScript Context)
  • ไม่ใช่ Query ปกติ ไม่ได้ใช้ Index
  • เหมาะสำหรับ Admin/DevOps Tasks
  • Driver ภาษาอื่น (Node.js, Python) ใช้ listCollections() แล้ว Filter ใน Application Code