Insert date in MongoDB collection with Vert.x 3

The out-of-box Vert.x event bus can only transport a few basic types as well as Buffer and JsonObject. There is no Date object among these types. So, to send a date across the event bus, it has to be converted to a long or a string.

It is often not ideal to save dates in Mongo as string or long as sorting and other computations may not happen as you would expect with dates. Other non-Vert.x Mongo clients may also expect that dates be stored in the native format.

Mongo has an ISODate object that can be used to store dates. In order to utilize that feature we have to tell Mongo that the string we are sending should be interpreted as an ISODate. Mongo includes a directive called ‘$date’ that can do this for us. All we have to do is supply the date we want to insert in ISO format.

In Vert.x we would need to create a JSON document that looks something like this:

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

This would tell Mongo to store an ISODate represented by the string in the ‘birthDate’ attribute.

So to prepare a document and save it to a Mongo collection we would do the following.

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

JsonObject document = new JsonObject();
document.put("name", "Kim Hilton");
document.put("birthDate", new JsonObject().put("$date", "2016-01-27T22:57:34.127Z"));"people", document, mongoHandler -> {
if (mongoHandler.succeeded()) [.. some happy code..]];
else if (mongoHandler.failed()) [.. some error handler..];

Once the save is complete, you can check your collection with the Mongo client and see that the birthDate was saved as an ISODate.

Here’s a working example in Java: MongoDateExampleVerticle

And some test cases that pass: MongoDateTest

Leave a Reply

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