บทความนี้แนะนำวิธีแสดงผล Query ใน MongoDB Shell ให้อ่านง่าย สวยขึ้น โดยใช้ findOne() (แสดง 1 Document) และ find().toArray() (แสดงทั้งหมดใน Array Format)
สร้างข้อมูลตัวอย่าง
> db.betterFormatDemo.insertOne({"StudentName":"Adam Smith","StudentScores":[98,67,89]});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd7ab826d78f205348bc640") }
> db.betterFormatDemo.insertOne({"StudentName":"John Doe","StudentScores":[67,89,56]});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd7ab936d78f205348bc641") }
> db.betterFormatDemo.insertOne({"StudentName":"Sam Williams","StudentScores":[45,43,33]});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd7aba76d78f205348bc642") }
แสดงผลแบบปกติ (find() - Cursor)
> db.betterFormatDemo.find();
{ "_id" : ObjectId("5cd7ab826d78f205348bc640"), "StudentName" : "Adam Smith", "StudentScores" : [ 98, 67, 89 ] }
{ "_id" : ObjectId("5cd7ab936d78f205348bc641"), "StudentName" : "John Doe", "StudentScores" : [ 67, 89, 56 ] }
{ "_id" : ObjectId("5cd7aba76d78f205348bc642"), "StudentName" : "Sam Williams", "StudentScores" : [ 45, 43, 33 ] }
Case 1: ใช้ findOne() - แสดง 1 Document แบบ Pretty
> db.betterFormatDemo.findOne();
{
"_id" : ObjectId("5cd7ab826d78f205348bc640"),
"StudentName" : "Adam Smith",
"StudentScores" : [
98,
67,
89
]
}
Case 2: ใช้ find().toArray() - แสดงทั้งหมดใน Array Format
> db.betterFormatDemo.find().toArray();
[
{
"_id" : ObjectId("5cd7ab826d78f205348bc640"),
"StudentName" : "Adam Smith",
"StudentScores" : [ 98, 67, 89 ]
},
{
"_id" : ObjectId("5cd7ab936d78f205348bc641"),
"StudentName" : "John Doe",
"StudentScores" : [ 67, 89, 56 ]
},
{
"_id" : ObjectId("5cd7aba76d78f205348bc642"),
"StudentName" : "Sam Williams",
"StudentScores" : [ 45, 43, 33 ]
}
]
ความแตกต่างและกรณีใช้งาน
| Method | คืนค่า | Format | เหมาะสำหรับ |
|---|---|---|---|
find() | Cursor | Pretty Print (Shell Auto) | Query แบบ Interactive, ข้อมูลเยอะ |
findOne() | Document (Object) | Pretty Print (Shell Auto) | ดู Document เดียว, Debug |
find().toArray() | Array of Documents | JSON Array Format | Copy/Export, Script Processing, Small Dataset |
เคล็ดลับเพิ่มเติม: Pretty Print แบบ Manual
// ใช้ printjson() ใน forEach db.collection.find().forEach(printjson); // หรือ format เองด้วย JSON.stringify db.collection.find().forEach(doc => print(JSON.stringify(doc, null, 2)));
ข้อควรระวัง toArray()
- โหลดข้อมูลทั้งหมดเข้าหน่วยความจำ (RAM) → อาจ Crash หากข้อมูลเยอะ
- ใช้กับ Dataset ขนาดเล็กหรือมี Limit เท่านั้น
- Production ให้ใช้ Cursor Streaming แทน