Consider exposing BSON format (kotlinx.serialization)

XMLWordPrintableJSON

    • Type: Improvement
    • Resolution: Unresolved
    • Priority: Unknown
    • None
    • Affects Version/s: None
    • Component/s: Kotlin
    • None
    • Java Drivers
    • None
    • None
    • None
    • None
    • None
    • None

      When using kotlinx.serialization outside the context of MongoDB, a format class is available to serialize and deserialize data. E.g. for JSON:

      val jsonFormat = Json { ignoreUnknownKeys = false }
      jsonFormat.decodeFromString<Person>("""{"name":"John Doe"}""")
      jsonFormat.encodeToString(Person(name="Jane Doe"))

      When using kotlinx.serialization with the Kotlin-MongoDB-Driver, such a format (e.g. BSON) is not available since it is hidden in the driver implementation.

      This has two drawbacks:

       

      1 Serialization tests

      Serialization tests answer the question: "Am I inserting the data in the intended format into the database?". E.g. it does matter whether I am storing a date as BSON date or as string. Or I might want to ensure a specific type discriminator field "type" vs. the default "_t" is used.

      This is currently only possible to test with starting up a MongoDB test-container, writing the data via the MongoDB client via a typed collection Collection<Person>, and reading it again via a raw collection such as Collection<Document> or Collection<BsonDocument>.

       

      2 Serialize entire queries or aggregations (maybe less important)

      Operations on collections such as collection.find or collection.aggregate take BSON and List<BSON> as parameters. BSON documents can either be created via a very cumbersome api such as:

      val bson = BsonDocument()
          .append("key1", "value1")
          .append(
              "key2",
              BsonDocument()
                  .append("key1", "value1")
                  .append("key2", "value2")
          )
      
      collection.find(bson)

      or via the handy DSL

      val findJohn = Filters.eq(Person::name, "John Doe")
      // or
      val findJane = Person::name eq "Jane Doe"
      
      collection.find(findJohn)
      collection.find(findJane)

      Since BSON is very flexible and thus complex, the DSL will probably never cover all use-cases for queries and aggregations.

      Exposing a BSON format would allow developers to write queries in a very flexible way. E.g.

      @Serializable
      class FindByIdQuery(
          @SerialName("_id")
          val id: String,
      )
      
      collection.find(bsonFormat.encode(FindByIdQuery("id")))

            Assignee:
            Unassigned
            Reporter:
            Richard Schielek
            None
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated: