I just realized you can do this:
BasicDBObject doc = new BasicDBObject( "name", "Matt" );collection.insert( doc );ObjectId id = (ObjectId)doc.get( "_id" );
To avoid casting from Object to ObjectId, given a com.mongodb.client.MongoCollection collection and a org.bson.Document doc, you can do the following:
Object
ObjectId
com.mongodb.client.MongoCollection collection
org.bson.Document doc
collection.insert(doc);ObjectId id = doc.getObjectId("_id");
It's safe to do
doc.set("_id", new ObjectId())
if you look at driver code
if ( ensureID && id == null ){ id = ObjectId.get(); jo.put( "_id" , id ); }public static ObjectId get(){ return new ObjectId();}