MongoDB에서 공백 없이 JSON 출력하기 – Unpretty JSON
MongoDB 셸에서 find() 메서드로 문서를 조회하면 결과가 한 줄로 출력되며, pretty() 메서드를 사용하면 들여쓰기가 적용된 읽기 좋은 형태로 표시됩니다. 반대로 공백과 줄바꿈 없이 한 줄로 압축된 JSON, 즉 예쁘지 않은(unpretty) JSON을 출력하고 싶다면 printjsononeline() 함수를 활용하면 됩니다.
기본 문법
공백 없이(unpretty) 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")
}pretty()로 조회한 결과
find() 메서드와 pretty()를 함께 사용하면 컬렉션의 모든 문서를 보기 좋게 출력할 수 있습니다.
> db.unprettyJsonDemo.find().pretty();
실행 결과는 다음과 같습니다.
{
"_id" : ObjectId("5c900df25705caea966c557d"),
"StudentName" : "John",
"StudentAge" : 21,
"StudentTechnicalSkills" : [
"C",
"C++"
]
}
{
"_id" : ObjectId("5c900e085705caea966c557e"),
"StudentName" : "Carol",
"StudentAge" : 22,
"StudentTechnicalSkills" : [
"MongoDB",
"MySQL"
]
}공백 없이(Unpretty) 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++" ] }정리
printjsononeline()은 각 문서를 단일 행으로 출력하므로 대량의 데이터를 로그 형태로 빠르게 확인할 때 유용합니다. 반면 사람이 읽고 디버깅하기 위한 목적이라면 pretty()가 더 적합합니다. 용도에 맞게 두 출력 방식을 선택적으로 사용하면 됩니다.