ดึงข้อมูลเฉพาะและจัดรูปแบบผลลัพธ์ใน MongoDB
บทความนี้สาธิตการใช้ find() พร้อมเงื่อนไข Query, Projection, Limit และ pretty() เพื่อจัดรูปแบบการแสดงผล
ขั้นตอนที่ 1: สร้าง Collection และเพิ่มข้อมูลตัวอย่าง
สร้าง collection ชื่อ getSpecificData มีโครงสร้าง Nested Document: Information.Place.CountryName
> db.getSpecificData.insertOne({
"StudentName": "John",
"Information": {
"FatherName": "Chris",
"Place": { "CountryName": "US", "ZipCode": "111344" },
"id": "1"
}
});
{ "acknowledged": true, "insertedId": ObjectId("5e039abdf5e889d7a5199509") }
// ... เพิ่มอีก 3 รายการ (Carol, David, Jace) ตามต้นฉบับ
ขั้นตอนที่ 2: ค้นหาข้อมูล CountryName = "US" พร้อม limit(2) และ pretty()
> db.getSpecificData.find(
{'Information.Place.CountryName': "US"},
{},
{limit: 2}
).pretty();
ผลลัพธ์: แสดง 2 รายการแรก แบบจัดรูปแบบสวยงาม (Pretty Print)
ขั้นตอนที่ 3: ค้นหาแบบเดียวกันแต่ไม่ใช้ pretty() (รูปแบบ Compact)
> db.getSpecificData.find(
{'Information.Place.CountryName': "US"},
{}
).limit(2);
ผลลัพธ์: แสดง 2 รายการแรก แบบบรรทัดเดียว (Compact)
สรุป:
find(query, projection, options)รองรับการระบุเงื่อนไข, ฟิลด์ที่ต้องการ, และตัวเลือกเช่น limitpretty()ใช้จัดรูปแบบ Output ให้อ่านง่าย (สำหรับ Shell/Console)- ใน Production Driver ควรใช้ Options object แทน chaining