Jen-Ming Chung

Convert ObjectId to String in MongoDB Asynchronous Java Driver

Here’s quick share of converting the ObjectId to String in MongoDB Asynchronous Java Driver:

1
2
3
4
5
6
7
Aggregate.Builder builder = new Aggregate.Builder();
...
Iterable<Document> docs = collection.aggregate(builder.build());
for (Document d : docs) {
    String objectIdString = ((ObjectIdElement)d.get("_id")).getId().toHexString();
    System.out.println(objectIdString);
}

Allanbank’s driver is a good alternative when 10gen driver does not provide a better way for constructing arbitrary Aggregation pipelines. Now the official MongoDB Java driver also provides a new helper method, DBCollection.aggregate() which can be used to create aggregation tasks since version 2.9.0.

Comments