개요
이 가이드 에서는 MongoDB 문서와 상호 작용할 때 확장 JSON 데이터 형식을 사용하는 방법을 학습 수 있습니다.
JSON 객체, 배열, 숫자, 문자열, 부울 및 null 값을 나타내는 사람이 읽을 수 있는 데이터 형식입니다. 이 형식은 MongoDB 데이터를 저장 데 사용하는 형식인 BSON 데이터 유형의 하위 집합만 지원합니다. 확장 JSON 형식은 더 많은 BSON 유형을 지원하며, BSON 의 각 유형에 직접적으로 대응하는 필드 유형 정보를 나타내기 위해 '$
' 접두사가 붙은 예약된 키 설정하다 정의합니다.
JSON, BSON 및 확장 JSON 에 대해 자세히 학습 JSON 및 BSON 리소스 및 확장 JSON MongoDB Server 수동 항목을 참조하세요.
확장 JSON 형식
MongoDB 확장 JSON BSON 데이터를 나타내는 문자열 형식을 제공합니다. 각 형식은 JSON RFC 를 준수하며 특정 사용 사례를 충족합니다.
다음 표에서는 각 확장 JSON 형식에 대해 설명합니다.
이름 | 설명 |
---|---|
확장 또는 표준 | A string format that avoids loss of BSON type information during data conversions. This format prioritizes type preservation at the loss of human-readability and
interoperability with older formats. To learn more about this format, see JsonMode.EXTENDED
in the API documentation. |
완화 | A string format that describes BSON documents with some type information loss. This format prioritizes human-readability and interoperability at the loss of
certain type information. The Kotlin Sync driver uses Relaxed mode by default.
To learn more about this format, see JsonMode.RELAXED
in the API documentation. |
Shell | A string format that matches the syntax used in the MongoDB shell. This format prioritizes compatibility with the MongoDB shell, which often uses
JavaScript functions to represent types. To learn more about this format, see JsonMode.SHELL
in the API documentation. |
참고
코틀린 동기 (Kotlin Sync) 운전자 문자열에서 $uuid
확장 JSON 유형을 바이너리 하위 유형 4의 BsonBinary
객체 로 구문 분석합니다. $uuid
필드 분석에 대한 자세한 내용은 확장 JSON 사양의 $uuid 필드 구문 분석을 위한 특수 규칙 섹션을 참조하세요.
확장 JSON 예시
다음 예시에서는 각 확장 JSON 형식으로 표시되는 ObjectId, 날짜, 긴 숫자 필드가 포함된 문서를 보여 줍니다. 원하는 형식의 예시 탭을 클릭합니다.
{ "_id": { "$oid": "573a1391f29313caabcd9637" }, "createdAt": { "$date": { "$numberLong": "1601499609" }}, "numViews": { "$numberLong": "36520312" } }
{ "_id": { "$oid": "573a1391f29313caabcd9637" }, "createdAt": { "$date": "2020-09-30T18:22:51.648Z" }, "numViews": 36520312 }
{ "_id": ObjectId("573a1391f29313caabcd9637"), "createdAt": ISODate("2020-09-30T18:22:51.648Z"), "numViews": NumberLong("36520312") }
확장 JSON 읽기
이 섹션에서는 다음과 같은 방법으로 확장 JSON 값을 코틀린 (Kotlin) 객체로 읽는 방법을 보여줍니다.
문서 클래스 사용
확장 JSON 문자열을 코틀린 (Kotlin) 문서 객체 로 읽으려면 Document
또는 BsonDocument
클래스에서 parse()
정적 메서드를 호출합니다. 이 메서드는 확장 JSON 문자열을 구문 분석하고 해당 데이터를 지정된 문서 클래스의 인스턴스 에 저장합니다.
다음 예시 에서는 parse()
메서드를 사용하여 확장 JSON 문자열을 Document
객체 로 읽습니다.
val ejsonStr = """ { "_id": { "$${"oid"}": "507f1f77bcf86cd799439011" }, "myNumber": { "$${"numberLong"}": "4794261" } } """.trimIndent() val doc = Document.parse(ejsonStr) println(doc)
Document{{_id=507f1f77bcf86cd799439011, myNumber=4794261}}
JsonReader 클래스 사용
코틀린 동기 (Kotlin Sync) 드라이버의 문서 클래스를 사용하지 않고 확장 JSON 문자열을 코틀린 (Kotlin) 객체로 읽으려면 BSON 라이브러리의 JsonReader
클래스를 사용하세요. 이 클래스에는 확장 JSON 문자열의 필드와 값을 순차적으로 구문 분석하고 이를 코틀린 (Kotlin) 객체로 반환하는 메서드가 포함되어 있습니다. 드라이버의 문서 클래스도 이 클래스를 사용하여 확장 JSON 구문 분석합니다.
다음 코드는 JsonReader
클래스에서 제공하는 메서드를 사용하여 확장 JSON 문자열을 코틀린 (Kotlin) 객체로 변환합니다.
val string = """ { "_id": { "$${"oid"}": "507f1f77bcf86cd799439011" }, "myNumber": { "$${"numberLong"}": "4794261" } } """.trimIndent() val jsonReader = JsonReader(string) jsonReader.readStartDocument() // Reads the "_id" field value jsonReader.readName("_id") val id = jsonReader.readObjectId() // Reads the "myNumber" field value jsonReader.readName("myNumber") val myNumber = jsonReader.readInt64() jsonReader.readEndDocument() println("$id is type: ${id::class.qualifiedName}") println("$myNumber is type: ${myNumber::class.qualifiedName}") jsonReader.close()
507f1f77bcf86cd799439011 is type: org.bson.types.ObjectId 4794261 is type: kotlin.Long
확장 JSON 쓰기
이 섹션에서는 다음과 같은 방법으로 코틀린 (Kotlin) 객체에서 확장 JSON 값을 쓰기 (write) 방법을 보여줍니다.
문서 클래스 사용
Document
또는 BsonDocument
객체 에서 확장 JSON 문자열을 쓰기 (write) 하려면 toJson()
메서드를 호출합니다. 이 메서드에 JsonWriterSettings
객체 매개변수를 전달하여 확장 JSON 형식을 지정할 수 있습니다.
다음 예시 Document
데이터를 완화 모드 확장 JSON 으로 씁니다.
val doc = Document() .append("_id", ObjectId("507f1f77bcf86cd799439012")) .append("createdAt", Date.from(Instant.ofEpochMilli(1601499609000L))) .append("myNumber", 4794261) val settings = JsonWriterSettings.builder() .outputMode(JsonMode.RELAXED) .build() println(doc.toJson(settings))
{"_id": {"$oid": "507f1f77bcf86cd799439012"}, "createdAt": {"$date": "2020-09-30T21:00:09Z"}, "myNumber": 4794261}
JsonWriter 클래스 사용
코틀린 (Kotlin) 객체에 저장된 데이터에서 확장 JSON 문자열을 출력하려면 BSON 라이브러리의 JsonWriter
클래스를 사용할 수 있습니다. JsonWriter
객체 구성하려면 Java Writer
의 하위 클래스를 전달하여 확장 JSON 출력할 방법을 지정합니다. 선택적으로 JsonWriterSettings
인스턴스 전달하여 확장 JSON 형식과 같은 옵션을 지정할 수 있습니다. 기본값 으로 JsonWriter
는 완화 모드 형식을 사용합니다. 코틀린 동기 (Kotlin Sync) 드라이버의 문서 클래스도 이 클래스를 사용하여 BSON 확장 JSON 으로 변환합니다.
다음 예시 JsonWriter
객체 사용하여 표준 모드 확장 JSON 문자열 값을 생성하고 이를 System.out
에 출력합니다.
val settings = JsonWriterSettings.builder() .outputMode(JsonMode.EXTENDED) .build() JsonWriter(BufferedWriter(OutputStreamWriter(System.out)), settings).use { jsonWriter -> jsonWriter.writeStartDocument() jsonWriter.writeName("_id") jsonWriter.writeObjectId(ObjectId("507f1f77bcf86cd799439012")) jsonWriter.writeName("myNumber") jsonWriter.writeInt64(11223344L) jsonWriter.writeEndDocument() jsonWriter.flush() }
{"_id": {"$oid": "507f1f77bcf86cd799439012"}, "myNumber": {"$numberLong": "11223344"}}
사용자 지정 BSON 유형 변환
확장 JSON 출력 형식을 지정하는 것 외에도 JsonWriterSettings
객체 에 변환기를 추가하여 출력을 추가로 사용자 지정할 수 있습니다. 이러한 변환기 메서드는 변환 프로세스 중에 다양한 데이터 유형을 처리하기 위한 로직을 지정합니다.
다음 예시 문서 클래스 사용 예시 와 동일한 문서 변환합니다. 그러나 이 예시 에서는 JsonWriterSettings
객체 에 objectIdConverter()
및 dateTimeConverter()
변환기 메서드를 정의하여 완화 모드 확장 JSON 출력을 간소화합니다.
val settings = JsonWriterSettings.builder() .outputMode(JsonMode.RELAXED) .objectIdConverter { value, writer -> writer.writeString(value.toHexString()) } .dateTimeConverter { value, writer -> val zonedDateTime = Instant.ofEpochMilli(value).atZone(ZoneOffset.UTC) writer.writeString(DateTimeFormatter.ISO_DATE_TIME.format(zonedDateTime)) } .build() val doc = Document() .append("_id", ObjectId("507f1f77bcf86cd799439012")) .append("createdAt", Date.from(Instant.ofEpochMilli(1601499609000L))) .append("myNumber", 4794261) println(doc.toJson(settings))
{"_id": "507f1f77bcf86cd799439012", "createdAt": "2020-09-30T21:00:09Z", "myNumber": 4794261}
API 문서
이 가이드에서 사용되는 메서드 또는 유형에 대해 자세히 알아보려면 다음 API 설명서를 참조하세요.