확장 JSON
개요
스칼라 드라이버는 MongoDB 확장 JSON으로 표시되는 BSON 문서의 읽기 및 쓰기를 지원합니다. 다음 변형이 모두 지원됩니다.
엄격 모드: JSON RFC 를 준수하는 BSON types 표현 . 이는 mongoexport 가 생성하고 mongoimport 가 사용하는 형식입니다.
셸 모드: MongoDB 셸 이 구문 분석할 수 있는 JSON의 상위 집합입니다.
또한 Document
유형은 이러한 목적으로 두 가지 편의 메서드 세트를 제공합니다.
Document.toJson()
:Document
인스턴스를 JSON 문자열로 변환하는 오버로드된 메서드 세트입니다.Document(<json>)
: JSON 문자열을Document
인스턴스로 변환하는 오버로드된 정적 팩토리 메서드 세트입니다.
JSON 작성
드라이버를 사용하여 mongoexport
와 유사한 도구를 구현하는 작업을 고려하세요.
val fileName = // initialize to the path of the file to write to val collection = // initialize the collection from which you want to query val writer: PrintWriter = new PrintWriter(fileName) collection.find().subscribe( (doc: Document) => output.write(s"${doc.toJson}\r\n"), (t: Throwable) => // handle failure, () => output.close())
Document.toJson()
메서드는 줄 바꿈이나 들여쓰기 없이 엄격 모드로 쓰는 기본 설정으로 JsonWriter
의 인스턴스를 구성합니다.
toJson()
의 오버로드 중 하나를 사용하여 이 기본 동작을 재정의할 수 있습니다. 예를 들어 복사하여 MongoDB Shell에 붙여넣을 수 있는 JSON 문자열을 작성하는 작업을 생각해 보겠습니다.
import java.text.SimpleDateFormat val fmt = new SimpleDateFormat("dd/MM/yy") val first = fmt.parse("01/01/2014") val second = fmt.parse("01/01/2015") val doc = Document("startDate" -> Document("$gt" -> first, "$lt" -> second)) println(doc.toJson(new JsonWriterSettings(JsonMode.SHELL)))
이 코드 스니펫은 MongoDB 셸과 호환되는 JSON을 출력한 다음 셸에 붙여넣을 수 있습니다.
{ "startDate" : { "$gt" : ISODate("2014-01-01T05:00:00.000Z"), "$lt" : ISODate("2015-01-01T05:00:00.000Z") } }
JSON 읽기
드라이버를 사용하여 mongoimport
와 유사한 도구를 구현하는 작업을 고려하세요.
import scala.io.Source val fileName = // initialize to the path of the file to read from val collection = // initialize the collection from which you want to import to try { for (json <- Source.fromFile(fileName).getLines()) { collection.insertOne(Document(json)).head() } } catch { case ex: Exception => println("Bummer, an exception happened.") }
Document(<json>)
컴패니언 헬퍼 메서드는 지정된 문자열을 사용하여 JsonReader
인스턴스를 구성하고 이에 상응하는 Document
인스턴스의 인스턴스를 반환합니다. JsonReader
는 문자열에서 JSON 플레이버를 자동으로 감지하므로 지정할 필요가 없습니다.
JSON 직접 읽기 및 쓰기
문서가 필요하지 않고 JSON만 처리하려는 경우 JsonObject
를 사용하여 JSON을 직접 읽고 쓸 수 있습니다. JsonObject
은 생성자에서 String
를 취하고 getJson()
메서드에서 String
을 반환하는 래퍼 클래스입니다. JSON을 직접 읽고 쓰는 것이 Document
을 먼저 구성한 다음 toJson()
을 호출하는 것보다 더 효율적이며 Document#parse()
을 호출하는 것보다 더 효율적입니다.
JSON 읽기/쓰기를 담당하는 코덱인 JsonObjectCodec
는 기본 레지스트리의 일부이므로 이 작업을 수행하는 것은 매우 간단하며 다음 예제를 통해 확인할 수 있습니다.
val database: MongoDatabase = mongoClient.getDatabase("mydb") val collection: MongoCollection[JsonObject] = database.getCollection("test") collection.insertOne(new JsonObject("{hello: 1}")).printResults() val jsonObject: SingleObservable[JsonObject] = collection.find.first()
CustomSettings로 JSON 읽기 및 쓰기
코덱을 직접 구성한 다음 레지스트리를 만들어 JsonObjectCodec
에 사용자 지정 JsonWriterSettings
를 제공할 수도 있습니다.
val codecRegistry = fromRegistries( fromCodecs(new JsonObjectCodec(JsonWriterSettings .builder() .outputMode(JsonMode.EXTENDED) .build())), DEFAULT_CODEC_REGISTRY ) val database: MongoDatabase = mongoClient.getDatabase("mydb").withCodecRegistry(codecRegistry) val collection: MongoCollection[JsonObject] = database.getCollection("test") collection.insertOne(new JsonObject("{hello: 1}")).printResults() val jsonObject: SingleObservable[JsonObject] = collection.find.first()