Overview
Scala驱动程序支持读取和写入表示为MongoDB Extended JSON的BSON文档。支持以下两种变体:
严格模式:符合JSON RFC 的BSON 类型表示。这是 mongoexport 生成且 mongoimport 使用的格式。
shell模式:JSON MongoDBshell可以解析的 超集。
此外,  Document类型为此目的提供了两组便捷方法:
Document.toJson():一设立重载方法,用于将Document实例转换为JSON stringDocument(<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()的重载之一来重写此默认行为。 JSONstring以编写可复制并粘贴到 中的MongoDBshell 的任务示例:
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 。 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()