Skip to main content
Version: v3.x (DDN)

Extended JSON

The MongoDB connector uses introspection to infer schemas for database collections. Those schemas specify a type for each document field. (See Types). Because MongoDB itself is schema-less, there are cases where document data does not fit neatly into a type description. For these cases the special scalar type, extendedJSON, is provided as an escape hatch. extendedJSON is the connector's "any" type - a field or input of type extendedJSON can have any value.

The situation that comes up most often is heterogeneous data: different documents in a collection contain different types of data under the same field name. For example consider a collection that has documents that have a createdAt field, and some of those documents use date values for that field while others use string values. Since Hasura does not implement union types there is no way to configure the connector for a field with type "either date or string". In this case the solution is to set the type of the field to extendedJSON. And that is what the introspection system does automatically when it samples data in this situation.

Another case that can come up is a desire to store dynamic data. For example, you may have a field that stores objects with arbitrary keys. Since Hasura does not implement a dictionary type that can't be expressed directly in connector configuration. Once again the solution is to set the field type to extendedJSON.

Conversion to JSON

GraphQL operates using JSON; to interact with BSON data in your database the connector must convert inputs (such as filter arguments or mutation inputs) from JSON to BSON, and must convert result data from BSON to JSON. These conversions are determined by the types configured in your connector's schema.

Values with the extendedJSON type convert differently than other types. (For conversions for other types see Representations in JSON.) extendedJSON values are converted to JSON according to the Extended JSON specification defined by MongoDB. This is the same format you get in mongosh when serializing values using EJSON. For example, EJSON.stringify(db.posts.findOne()). Unlike JSON representations for other types, Extended JSON includes inline type tags to preserve type information about the original BSON values. For example when the BSON value 3 is converted to JSON using Extended JSON the result looks like this:

{ "$numberInt": "3" }

Extended JSON has two modes: canonical and relaxed. Canonical mode is fully lossless, while relaxed mode can be nicer to work with. The connector can be configured to use the format that you prefer using the serializationOptions.extendedJSONMode option. See Root Configuration File.