Working with MongoDB is really cool. Is easy to setup and use any API in pretty much any programming lang out there. When you work in Java like me you will have a few challenges. First of all what I hate from Java and love from NodeJS is the dynamic creation of objects using directly JSON. This is also a nice ability of C#. Now when you need to serialize java objects to JSON to transform into data objects for the Mongo driver you will find GSON (google json parser) really useful but one of the problems will be that one of the types will be transformed to string, not to the type you really want inside Mongo. Dates.

So the solution for this case if you don’t use Spring Data Mongo or Morphia is to create and register a GSON converter with this code.

private static final String MONGO_UTC_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";

public JsonElement serialize(Date src, Type type, JsonSerializationContext context) {
  if (src == null) {
    return null;
  } else {
    SimpleDateFormat format = new SimpleDateFormat(MONGO_DATE_FORMAT);
    JsonObject jo = new JsonObject();
    jo.addProperty("$date", format.format(src));
    return jo;
public Date deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {
  Date date = null;
  SimpleDateFormat format = new SimpleDateFormat(MONGO_DATE_FORMAT);
    try {
      date = format.parse(json.getAsJsonObject().get("$date").getAsString());
    } catch (ParseException e) {
      date = null;
  return date;
Categories: databasenosql

Rodrigo Asensio

Apasionado por la tecnología

Leave a Reply

Your email address will not be published. Required fields are marked *