개요
Scala 운전자 는 확장 으로 표시되는 BSON 문서의 읽기 및 쓰기를 MongoDB JSON지원합니다. 다음 변형이 모두 지원됩니다.
엄격 모드: JSON RFC 을 준수하는 BSON types 표현입니다. 이는 mongoexport 가 생성하고 mongoimport 가 사용하는 형식입니다.
shell 모드: 이 JSON MongoDB shell 구문 분석할 수 있는 의 상위 집합입니다.
또한 Document 유형은 이러한 목적으로 두 가지 편의 메서드 세트를 제공합니다.
Document.toJson():Document인스턴스 를 JSON string로 변환하는 오버로드된 메서드 설정하다 입니다.Document(<json>): JSON string 을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() 의 오버로드 중 하나를 사용하여 이 기본값 동작을 재정의할 수 있습니다. 예를 예시, 에 복사하여 JSON string 붙여넣을 수 있는 을 작성하는 작업 을 생각해 MongoDB shell 보겠습니다.
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 shell과 호환되는 JSON 을 출력한 다음 shell 에 붙여넣을 수 있습니다.
{ "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>) 컴패니언 헬퍼 메서드는 지정된 string 을 사용하여 JsonReader 인스턴스 를 구성하고 이에 상응하는 Document 인스턴스 의 인스턴스 를 반환합니다. JsonReader JSON 는 에서 플레이버를 자동으로 string 감지하므로 지정할 필요가 없습니다.
JSON 직접 읽기 및 쓰기
문서 가 필요하지 않고 JSON 만 처리하려는 경우 JsonObject 를 사용하여 JSON 을 직접 읽고 쓰기 (write) 수 있습니다. JsonObject 은 생성자에서 String 를 취하고 getJson() 메서드에서 String 을 반환하는 래퍼 클래스입니다. JSON 을 직접 읽고 쓰는 것이 Document 을 먼저 구성한 다음 toJson() 을 호출하는 것보다 더 효율적이며 Document#parse() 을 호출하는 것보다 더 효율적입니다.
JSONJsonObjectCodec 읽기/쓰기를 담당하는 코덱은 기본값 레지스트리의 일부이므로 이 작업을 수행하는 것은 매우 간단하며 다음 예시 통해 확인할 수 있습니다.
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()