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++" ] }

更新於:30-Jul-2019

607 瀏覽量

開啟您的 職業生涯

完成課程認證

開始
廣告
© . All rights reserved.