Encode

Encode is auto detected for clojure maps or java documents.
So we don't need to do anything for example to insert clojure maps or java documents

Encode is needed for pojo ,see bellow.

Decode

Decode normally in Java driver needs a registry and a result class
Because we use the same class for Clojure and and Java,the Document class,we only need to give the registry we want.

For pojo we give both registry and result class.

Default decode

  • Set the default decode method to be in Clojure

    Create a MongoClientSettings,with the clj-registry

    (update-defaults :client-settings (-> (MongoClientSettings/builder)
    (.codecRegistry clj-registry)
    (.build)))
    (update-defaults :client (MongoClients/create (defaults :client-settings)))

    *defaults is a Clojure map with the default settings

  • Set the default decode method to be in Java

    Create a MongoClientSettings,no need to give a registry

    (update-defaults :client-settings (-> (MongoClientSettings/builder)
    (.build)))
    (update-defaults :client (MongoClients/create (defaults :client-settings)))

Those methods can be called from a Java program also but here are shown only in Clojure

Query decode

If we dont want to use the default decode method,we set it the different decode when we call the query.
Here we assume that the default is clj-registry and we want to use j-registry.

  • Command call
(def acoll ....)
(def j-acoll (.withCodecRegistry j-registry))
(q j-coll
(= :name "John"))

This can work also

(q {:registry j-registry
:coll-name acoll-name
:db-name adb-name}
(= :name "John"))
  • Method call

Before calling set the registry

(.WithCodecRegistry mycoll j-registry) ;;needed only if default is clj
(.WithCodecRegistry mycoll clj-registry)

If it is a database method

(.WithCodecRegistry mydb j-registry)
(.WithCodecRegistry mydb clj-registry)

If it a client method like listDatabaseNames we need to create a new Client with the registry we want

Pojo

With clojure and java,we gave only a registry.
Also we ignored the encode because its auto-found.

With Pojo we have to give the encode from/decode to class,and the registry.

cMQL provides a pojo-registry(driver.settings),which is the default pojo decode the automatic way.
If you make a custom pojo-registry use your registry.

(def db (.withCodecRegistry (.getDatabase (defaults :client) "sample_training")
pojo-registry))
(def grades-coll (.withCodecRegistry (.getCollection db "grades" Grade)
pojo-registry))
(insert grades-coll (Grade.)) ;;encode one instance of Grade class
(c-take-all (q grades-coll (limit 1))) ;;aggregate and decode to Grade class

Converting documents

We can also convert documents.
Those 2 methodsa are inside driver.document namespace

(clj->J-doc ajavadoc) ;;clojure map to java Document
(j-doc->clj aclojuremap) ;;java document to clojure map