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

หา Collections ทั้งหมดที่มีฟิลด์เฉพาะใน MongoDB

สแกนทุก Collection ใน Database เพื่อหาที่มีฟิลด์ที่ต้องการ

ใช้ db.getCollectionNames() วนลูปทุก Collection แล้ว find() พร้อม $exists: true ตรวจสอบฟิลด์

คำสั่ง: หา Collection ที่มีฟิลด์ "StudentFirstName"

> db.getCollectionNames().forEach(function(myCollectionName) {
    var frequency = db[myCollectionName].find({"StudentFirstName": {$exists: true}}).count();
    if (frequency > 0) {
        print(myCollectionName);
    }
});

ผลลัพธ์ตัวอย่าง

multiDimensionalArrayProjection
removeKeyFieldsDemo
stringOrIntegerQueryDemo

ตรวจสอบยืนยันกับ Collection หนึ่ง

> db.removeKeyFieldsDemo.find({"StudentFirstName": {$exists: true}});
{ "_id" : ObjectId("5cc6c8289cb58ca2b005e672"), "StudentFirstName" : "John", "StudentLastName" : "Doe" }
{ "_id" : ObjectId("5cc6c8359cb58ca2b005e673"), "StudentFirstName" : "John", "StudentLastName" : "Smith" }

วิธีทันสมัยกว่า (MongoDB 3.0+): ใช้ listCollections + $expr

// ได้ข้อมูลเมตาทุก Collection พร้อมกัน
db.runCommand({ listCollections: 1, filter: { "options.capped": false } })
    .cursor.firstBatch
    .forEach(coll => {
        var count = db[coll.name].countDocuments({ StudentFirstName: { $exists: true } });
        if (count > 0) print(coll.name);
    });

เคล็ดลับประสิทธิภาพ

  • สร้าง Index บนฟิลด์ที่ค้นหาบ่อย เพื่อทำให้ countDocuments() เร็วขึ้น
  • ใช้ countDocuments() แทน count() (Deprecated)
  • จำกัด Scope: รันใน Database ที่เกี่ยวข้องเท่านั้น
  • Parallelize: แบ่ง Collections ให้หลาย Thread/Process รันพร้อมกัน

Use Cases

  • Data Governance: ตรวจสอบ Schema Compliance
  • Migration: หา Collections ที่ต้อง Migrate Field
  • Auditing: ตรวจสอบว่าฟิลด์ใหม่ถูก Deploy ครบแล้วหรือยัง