Overview
In this guide, you can learn how to use the Extended JSON data format when interacting with MongoDB documents.
JSON is a human-readable data format that represents the values of objects,
arrays, numbers, strings, booleans, and nulls. This format supports only a
subset of BSON data types, which is the format that MongoDB uses to store data. The
Extended JSON format supports more BSON types, defining a reserved
set of keys prefixed with "$
" to represent field type information that
directly corresponds to each type in BSON.
To learn more about JSON, BSON, and Extended JSON, see the JSON and BSON resource and Extended JSON MongoDB Server manual entry.
Extended JSON Formats
MongoDB Extended JSON provides string formats to represent BSON data. Each format conforms to the JSON RFC and meets specific use cases.
The following table describes each Extended JSON format:
Name | Description |
---|---|
Extended or Canonical | A string format that avoids loss of BSON type information during data conversions. This format prioritizes type preservation at the loss of human-readability and
interoperability with older formats. |
Relaxed | A string format that describes BSON documents with some type information loss. This format prioritizes human-readability and interoperability at the loss of
certain type information. The Kotlin Sync driver uses Relaxed mode by default. |
Shell | A string format that matches the syntax used in the MongoDB shell. This format prioritizes compatibility with the MongoDB shell, which often uses
JavaScript functions to represent types. |
Note
The Kotlin Sync driver parses the $uuid
Extended JSON type from a string to a
BsonBinary
object of binary subtype 4. For more information about $uuid
field
parsing, see the
special rules for parsing $uuid fields
section in the extended JSON specification.
Extended JSON Examples
The following examples show a document containing an ObjectId, date, and long number field represented in each Extended JSON format. Click the tab that corresponds to the format of the example you want to see:
{ "_id": { "$oid": "573a1391f29313caabcd9637" }, "createdAt": { "$date": { "$numberLong": "1601499609" }}, "numViews": { "$numberLong": "36520312" } }
{ "_id": { "$oid": "573a1391f29313caabcd9637" }, "createdAt": { "$date": "2020-09-30T18:22:51.648Z" }, "numViews": 36520312 }
{ "_id": ObjectId("573a1391f29313caabcd9637"), "createdAt": ISODate("2020-09-30T18:22:51.648Z"), "numViews": NumberLong("36520312") }
Read Extended JSON
This section shows how to read Extended JSON values into Kotlin objects in the following ways:
Use the Document Classes
To read a Extended JSON string into a Kotlin document object, call
the parse()
static method from the Document
or BsonDocument
class.
This method parses the Extended JSON string and stores its data in an instance of the specified
document class.
The following example uses the parse()
method to read an Extended JSON string
into a Document
object:
val ejsonStr = """ { "_id": { "$${"oid"}": "507f1f77bcf86cd799439011" }, "myNumber": { "$${"numberLong"}": "4794261" } } """.trimIndent() val doc = Document.parse(ejsonStr) println(doc)
Document{{_id=507f1f77bcf86cd799439011, myNumber=4794261}}
Use the JsonReader Class
To read an Extended JSON string into Kotlin objects without using
the Kotlin Sync driver's document classes, use the BSON library's JsonReader
class.
This class contains methods to sequentially parse the fields and values
of the Extended JSON string and return them as Kotlin objects.
The driver's document classes also use this class to parse Extended JSON.
The following code uses methods provided by the JsonReader
class to convert
an Extended JSON string into Kotlin objects:
val string = """ { "_id": { "$${"oid"}": "507f1f77bcf86cd799439011" }, "myNumber": { "$${"numberLong"}": "4794261" } } """.trimIndent() val jsonReader = JsonReader(string) jsonReader.readStartDocument() // Reads the "_id" field value jsonReader.readName("_id") val id = jsonReader.readObjectId() // Reads the "myNumber" field value jsonReader.readName("myNumber") val myNumber = jsonReader.readInt64() jsonReader.readEndDocument() println("$id is type: ${id::class.qualifiedName}") println("$myNumber is type: ${myNumber::class.qualifiedName}") jsonReader.close()
507f1f77bcf86cd799439011 is type: org.bson.types.ObjectId 4794261 is type: kotlin.Long
Write Extended JSON
This section shows how to write Extended JSON values from Kotlin objects in the following ways:
Use the Document Classes
To write an Extended JSON string from a Document
or BsonDocument
object, call the toJson()
method. You can pass this method a
JsonWriterSettings
object parameter to specify the Extended JSON format.
The following example writes Document
data as Relaxed mode Extended
JSON:
val doc = Document() .append("_id", ObjectId("507f1f77bcf86cd799439012")) .append("createdAt", Date.from(Instant.ofEpochMilli(1601499609000L))) .append("myNumber", 4794261) val settings = JsonWriterSettings.builder() .outputMode(JsonMode.RELAXED) .build() println(doc.toJson(settings))
{"_id": {"$oid": "507f1f77bcf86cd799439012"}, "createdAt": {"$date": "2020-09-30T21:00:09Z"}, "myNumber": 4794261}
Use the JsonWriter Class
To output an Extended JSON string from data stored in Kotlin objects, you can use
the BSON library's JsonWriter
class. To construct a JsonWriter
object,
pass a subclass of a Java Writer
to specify how you want to output the Extended
JSON. Optionally, you can pass a JsonWriterSettings
instance to specify options,
such as the Extended JSON format. By default, JsonWriter
uses the Relaxed mode
format. The Kotlin Sync driver's document classes also use this class to convert BSON
to Extended JSON.
The following example uses a JsonWriter
object to create
Canonical mode Extended JSON string values and output them to System.out
:
val settings = JsonWriterSettings.builder() .outputMode(JsonMode.EXTENDED) .build() JsonWriter(BufferedWriter(OutputStreamWriter(System.out)), settings).use { jsonWriter -> jsonWriter.writeStartDocument() jsonWriter.writeName("_id") jsonWriter.writeObjectId(ObjectId("507f1f77bcf86cd799439012")) jsonWriter.writeName("myNumber") jsonWriter.writeInt64(11223344L) jsonWriter.writeEndDocument() jsonWriter.flush() }
{"_id": {"$oid": "507f1f77bcf86cd799439012"}, "myNumber": {"$numberLong": "11223344"}}
Custom BSON Type Conversion
In addition to specifying the Extended JSON output format, you
can further customize the output by adding converters to your
JsonWriterSettings
object. These converter methods specify logic
for handling different data types during the conversion process.
The following example converts the same document as the Use the Document Classes
example. However, this example defines the objectIdConverter()
and dateTimeConverter()
converter methods in a JsonWriterSettings
object to simplify the Relaxed mode
Extended JSON output:
val settings = JsonWriterSettings.builder() .outputMode(JsonMode.RELAXED) .objectIdConverter { value, writer -> writer.writeString(value.toHexString()) } .dateTimeConverter { value, writer -> val zonedDateTime = Instant.ofEpochMilli(value).atZone(ZoneOffset.UTC) writer.writeString(DateTimeFormatter.ISO_DATE_TIME.format(zonedDateTime)) } .build() val doc = Document() .append("_id", ObjectId("507f1f77bcf86cd799439012")) .append("createdAt", Date.from(Instant.ofEpochMilli(1601499609000L))) .append("myNumber", 4794261) println(doc.toJson(settings))
{"_id": "507f1f77bcf86cd799439012", "createdAt": "2020-09-30T21:00:09Z", "myNumber": 4794261}
API Documentation
To learn more about any of the methods or types discussed in this guide, see the following API documentation: