Skip to content

Instantly share code, notes, and snippets.

Created March 6, 2015 21:07
Show Gist options
  • Select an option

  • Save anonymous/a740e8a2a1d2e3a37cf4 to your computer and use it in GitHub Desktop.

Select an option

Save anonymous/a740e8a2a1d2e3a37cf4 to your computer and use it in GitHub Desktop.
Demonstrate how to add multiple codecs to the default registry.
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.ServerAddress;
import org.bson.Document;
import org.bson.UuidRepresentation;
import org.bson.codecs.UuidCodec;
import org.bson.codecs.configuration.CodecRegistry;
import java.util.UUID;
import static org.bson.codecs.configuration.CodecRegistries.fromCodecs;
import static org.bson.codecs.configuration.CodecRegistries.fromRegistries;
public class CodecTest {
public static void main(String[] args) {
MongoClientOptions.Builder builder = MongoClientOptions.builder();
CodecRegistry codecRegistry = fromRegistries(fromCodecs(new UuidCodec(UuidRepresentation.STANDARD),
new SqlDateCodec()),
MongoClient.getDefaultCodecRegistry());
builder.codecRegistry(codecRegistry);
MongoClientOptions options = builder.build();
MongoClient client = new MongoClient(new ServerAddress(), options);
client.getDatabase("test").getCollection("test").insertOne(new Document("_id", UUID.randomUUID())
.append("date", new java.sql.Date(System.currentTimeMillis())));
}
}
@jyemin

jyemin commented Mar 6, 2015

Copy link
Copy Markdown

Note that the SqlDateCodec referenced above is not included in the driver. It's just there as an example of how you can write your own Codec implementation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment