MongoDB 输出 JSON 无空格,即打印未经美化的 JSON?
要打印未经美化的 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++" ] }
广告