Để in json unretty, hãy sử dụng cú pháp sau -
var yourVariableName= db.yourCollectionName.find().sort({_id:-1}).limit(10000);
while( yourVariableName.hasNext() ) {
printjsononeline(yourVariableName.next() );
}; Để hiểu cú pháp, chúng ta hãy tạo một bộ sưu tập với tài liệu. Truy vấn để tạo một bộ sưu tập với một tài liệu như sau -
> 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")
} tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find (). Truy vấn như sau -
> db.unprettyJsonDemo.find().pretty();
Sau đây là kết quả -
{
"_id" : ObjectId("5c900df25705caea966c557d"),
"StudentName" : "John",
"StudentAge" : 21,
"StudentTechnicalSkills" : [
"C",
"C++"
]
}
{
"_id" : ObjectId("5c900e085705caea966c557e"),
"StudentName" : "Carol",
"StudentAge" : 22,
"StudentTechnicalSkills" : [
"MongoDB",
"MySQL"
]
} Đây là truy vấn để in JSON không có khoảng trắng, tức là JSON không có khoảng trắng -
> var myCursor = db.unprettyJsonDemo.find().sort({_id:-1}).limit(10000);
> while(myCursor.hasNext()){
... printjsononeline(myCursor.next());
... }; Sau đây là kết quả -
{ "_id" : ObjectId("5c900e085705caea966c557e"), "StudentName" : "Carol", "StudentAge" : 22, "StudentTechnicalSkills" : [ "MongoDB", "MySQL" ] }
{ "_id" : ObjectId("5c900df25705caea966c557d"), "StudentName" : "John", "StudentAge" : 21, "StudentTechnicalSkills" : [ "C", "C++" ] }