扩展JSON
概述
Scala驱动程序支持以MongoDB扩展JSON表示形式读取和写入BSON文档。以下两种变体都受支持:
严格模式:符合JSON RFC规范的BSON类型表示JSON RFC。这是mongoexport生成的格式,也是mongoimport消费的格式。
Shell模式:MongoDB shell可以解析的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 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>)
伴随辅助方法使用给定的字符串构造一个 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()