要打印不漂亮的json,请使用以下语法-
var yourVariableName= db.yourCollectionName.find().sort({_id:-1}).limit(10000); while( yourVariableName.hasNext() ) { printjsononeline(yourVariableName.next() ); };
为了理解语法,让我们用文档创建一个集合。使用文档创建集合的查询如下-
> 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") }
find()
方法帮助下集合中的所有文档。查询如下-
> db.unprettyJsonDemo.find().pretty();
以下是输出-
{ "_id" : ObjectId("5c900df25705caea966c557d"), "StudentName" : "John", "StudentAge" : 21, "StudentTechnicalSkills" : [ "C", "C++" ] } { "_id" : ObjectId("5c900e085705caea966c557e"), "StudentName" : "Carol", "StudentAge" : 22, "StudentTechnicalSkills" : [ "MongoDB", "MySQL" ] }
这是打印不带空格的JSON的查询,即不正确的JSON-
> 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++" ] }