เข้าถึง Collection ที่ชื่อขึ้นต้นด้วย _ ด้วย db.getCollection()
ใน MongoDB Shell ไม่สามารถใช้ Dot Notation เข้าถึง Collection ที่ชื่อขึ้นต้นด้วยอักขระพิเศษ (เช่น _, -, space) ได้ ต้องใช้ db.getCollection("name") แทน
สร้าง Collection ชื่อขึ้นต้นด้วย _
> db.createCollection('_testUnderscoreCollectionDemo');
{ "ok" : 1 }
Insert ข้อมูลผ่าน getCollection
> db.getCollection('_testUnderscoreCollectionDemo').insertOne({"StudentFirstName":"John","StudentAge":23});
> db.getCollection('_testUnderscoreCollectionDemo').insertOne({"StudentFirstName":"Carol","StudentAge":21});
Query ข้อมูล
> db.getCollection('_testUnderscoreCollectionDemo').find().pretty();
{ "_id" : ObjectId("5ccfb4a6140b992277dae0e4"), "StudentFirstName" : "John", "StudentAge" : 23 }
{ "_id" : ObjectId("5ccfb4af140b992277dae0e5"), "StudentFirstName" : "Carol", "StudentAge" : 21 }
กรณีอื่นที่ต้องใช้ getCollection()
| Collection Name | ปัญหา | Solution |
|---|---|---|
_private | ขึ้นต้น _ | db.getCollection("_private") |
my-collection | มี Hyphen (-) | db.getCollection("my-collection") |
my collection | มี Space | db.getCollection("my collection") |
123numbers | ขึ้นต้นตัวเลข | db.getCollection("123numbers") |
collection@name | มี Special Char | db.getCollection("collection@name") |
ตัวแปร Collection Reference
// กำหนดตัวแปรสั้นๆ
var coll = db.getCollection('_testUnderscoreCollectionDemo');
coll.find();
coll.insertOne({...});
coll.updateOne({...}, {...});
coll.drop();
ดูรายชื่อ Collections ทั้งหมด (รวมที่ขึ้นต้น _)
> db.getCollectionNames()
[ "_testUnderscoreCollectionDemo", "otherCollection", "another_one" ]
สรุป
- Collection Name ที่ไม่ใช่ Valid JS Identifier ต้องใช้
db.getCollection("name") - Valid JS Identifier: เริ่มต้นด้วย Letter, _, $ แล้วตามด้วย Letter, Digit, _, $
- แนะนำ: ตั้งชื่อ Collection เป็น camelCase หรือ snake_case ไม่ต้องใช้ Special Char