Để hiển thị kết quả truy vấn đẹp mắt, dễ đọc trong MongoDB shell, bạn sử dụng phương thức pretty() trên con trỏ (cursor).
Cú pháp
db.yourCollectionName.find().pretty();
Ví dụ minh họa
Tạo collection và dữ liệu
> db.prettyDemo.insertOne({"ClientName":"Larry","ClientAge":27,"ClientFavoriteCountry":["US","UK"]});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8a440de01f572ca0ccf5f2") }
> db.prettyDemo.insertOne({"ClientName":"Mike","ClientAge":57,"ClientFavoriteCountry":["AUS","UK"]});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8a4420e01f572ca0ccf5f3") }
Hiển thị không dùng pretty()
> db.prettyDemo.find();
{"_id" : ObjectId("5c8a440de01f572ca0ccf5f2"), "ClientName" : "Larry", "ClientAge" : 27, "ClientFavoriteCountry" : [ "US", "UK" ]}
{"_id" : ObjectId("5c8a4420e01f572ca0ccf5f3"), "ClientName" : "Mike", "ClientAge" : 57, "ClientFavoriteCountry" : [ "AUS", "UK" ]}
Hiển thị có dùng pretty()
> db.prettyDemo.find().pretty();
{
"_id" : ObjectId("5c8a440de01f572ca0ccf5f2"),
"ClientName" : "Larry",
"ClientAge" : 27,
"ClientFavoriteCountry" : [
"US",
"UK"
]
}
{
"_id" : ObjectId("5c8a4420e01f572ca0ccf5f3"),
"ClientName" : "Mike",
"ClientAge" : 57,
"ClientFavoriteCountry" : [
"AUS",
"UK"
]
}
Đặt pretty() làm mặc định
Nếu bạn muốn pretty() luôn được bật mặc định, bạn có thể thêm vào file cấu hình .mongorc.js (tạo file này ở thư mục home nếu chưa có):
DBQuery.prototype._prettyShell = true;
Khởi động lại MongoDB shell, từ nay mọi lệnh find() sẽ tự động hiển thị đẹp mà không cần gọi .pretty().