Để in JSON dạng compact (một dòng, không whitespace) trong MongoDB shell, bạn sử dụng hàm printjsononeline() trong vòng lặp cursor.
Cú pháp
var cursor = db.collection.find().sort({_id:-1}).limit(10000);
while(cursor.hasNext()) {
printjsononeline(cursor.next());
};
Ví dụ minh họa
Tạo collection và dữ liệu
> db.unprettyJsonDemo.insertOne({"StudentName":"John","StudentAge":21,"StudentTechnicalSkills":["C","C++"]});
{ "acknowledged" : true, "insertedId" : ObjectId("5c900df25705caea966c557d") }
> db.unprettyJsonDemo.insertOne({"StudentName":"Carol","StudentAge":22,"StudentTechnicalSkills":["MongoDB","MySQL"]});
{ "acknowledged" : true, "insertedId" : ObjectId("5c900e085705caea966c557e") }
Xem dữ liệu pretty (mặc định)
> db.unprettyJsonDemo.find().pretty();
{
"_id" : ObjectId("5c900df25705caea966c557d"),
"StudentName" : "John",
"StudentAge" : 21,
"StudentTechnicalSkills" : [ "C", "C++" ]
}
{
"_id" : ObjectId("5c900e085705caea966c557e"),
"StudentName" : "Carol",
"StudentAge" : 22,
"StudentTechnicalSkills" : [ "MongoDB", "MySQL" ]
}
In unpretty JSON (compact)
> var myCursor = db.unprettyJsonDemo.find().sort({_id:-1}).limit(10000);
> while(myCursor.hasNext()){
printjsononeline(myCursor.next());
};
{"_id":ObjectId("5c900e085705caea966c557e"),"StudentName":"Carol","StudentAge":22,"StudentTechnicalSkills":["MongoDB","MySQL"]}
{"_id":ObjectId("5c900df25705caea966c557d"),"StudentName":"John","StudentAge":21,"StudentTechnicalSkills":["C","C++"]}
So sánh các phương thức in
| Phương thức | Định dạng | Use case |
|---|---|---|
printjson() | Pretty (multi-line, indented) | Đọc dễ, debug |
printjsononeline() | Compact (single line) | Log file, pipe to tool, export |
tojson() | Trả về string JSON | Xử lý string, concat |
tojsononeline() | Trả về string JSON 1 dòng | Ghi file, network transfer |
Xuất ra file (export)
// Trong shell, redirect output
mongo --quiet --eval "
var cursor = db.collection.find();
while(cursor.hasNext()) {
printjsononeline(cursor.next());
}
" > export.jsonl
Tạo file JSON Lines (mỗi dòng 1 JSON hợp lệ) - định dạng phổ biến cho big data processing.
Lưu ý
printjsononelinechỉ có trong MongoDB shell, không có trong driver- Dùng
JSON.stringify(doc)trong Node.js driver - Compact format tiết kiệm bandwidth khi truyền log/export