Read date from MongoDB collection with Vert.x 3

MongoDB is able to store dates natively as ISODates. Since Vert.x is not able to transport an ISODate object across the event bus, they are returned as ISO strings within a special JsonObject.

When reading an ISODate from a collection, it will be returned in a JSON object that looks something like this:

{"birthDate" : {"$date" : "2016-01-27T22:57:34.132Z"}}

So, to access the date string you would need to do this:

String sDate = json.getJsonObject("birthDate").getString("$date");

Here’s an example where we are reading a document from a Mongo collection and replying to an event bus consumer.

MongoClient mongoClient = MongoClient.createShared(vertx, config());

JsonObject query = new JsonObject().put("name", person.getString("name"));

mongoClient.findOne(COLLECTION_NAME, query, null, mongoHandler -> {
if (mongoHandler.succeeded()) {

  JsonObject found = mongoHandler.result();

  JsonObject reply = new JsonObject().put("name", found.getString("name"));
  if (found.containsKey("birthDate")) {
    reply.put("birthDate", found.getJsonObject("birthDate").getString("$date"));

} else if (mongoHandler.failed()), mongoHandler.cause().getMessage());

Here is a working example of reading a date from Mongo: MongoDateExampleVerticle (look for the “” consumer)

Here is a test case: MongoDateTest

Leave a Reply

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