MongoDB Shell cung cấp nhiều cách để hiển thị kết quả truy vấn dễ đọc hơn: findOne() cho một tài liệu, find().toArray() cho mảng tài liệu, và pretty() cho định dạng indentation.
Tạo dữ liệu mẫu
> 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") }
Hiển thị mặc định (compact)
> db.betterFormatDemo.find();
Cách 1: findOne() - Xem 1 tài liệu đẹp
> db.betterFormatDemo.findOne();Cách 2: find().toArray() - Xem tất cả dưới dạng mảng
> db.betterFormatDemo.find().toArray();Cách 3: find().pretty() - Định dạng indentation (mặc định cho shell)
> db.betterFormatDemo.find().pretty();Tương tự
findOne()nhưng cho nhiều tài liệu.So sánh các phương pháp
| Phương pháp | Trả về | Định dạng | Phù hợp |
|---|---|---|---|
find() | Cursor | Compact (1 dòng) | Lập trình, iteration |
findOne() | Document | Pretty (multi-line) | Xem 1 tài liệu nhanh |
find().pretty() | Cursor | Pretty (multi-line) | Debug shell, đọc nhiều doc |
find().toArray() | Array | Pretty (JSON array) | Copy/paste, export JSON |
Các tùy chọn hiển thị khác
Chỉ hiển thị các trường cụ thể
db.betterFormatDemo.find({}, {StudentName: 1, _id: 0}).pretty();
Giới hạn số lượng
db.betterFormatDemo.find().limit(2).pretty();
Sắp xếp trước khi xem
db.betterFormatDemo.find().sort({StudentName: 1}).pretty();
Trong MongoDB Compass / GUI tools
Các công cụ GUI (MongoDB Compass, Studio 3T, NoSQLBooster) cung cấp giao diện bảng (Table view), Tree view, JSON view đẹp mắt hơn shell.
Lưu ý
pretty()vàtoArray()chỉ hoạt động trong MongoDB Shell- Driver (Node.js, Python...) trả về cursor/array gốc, format tùy thư viện
toArray()tải toàn bộ kết quả vào bộ nhớ - cẩn thận với result set lớn