Overview
Scala ドライバーは、MongoDB 拡張 JSON として表される BSON ドキュメントの読み取りと書込みをサポートしています。 次の両方のバリアントがサポートされています。
厳密モード: JSON RFC に準拠するBSON型の表現。mongoexport が生成し、mongoimport が消費する形式です。
shellモード:JSON MongoDBshellが解析できる のスーパーセット。
さらに、  Documentタイプは、この目的のための便利なメソッドを 2 セット提供します。
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()のオーバーロードのいずれかを使用することで上書きできます。 例として、コピーして MongoDB shell に貼り付けることができる JSON string を書き込むタスクを考えてみましょう。
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は string 内の 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()