Get ID of last inserted document in a mongoDB w/ Java driver

I just realized you can do this:

BasicDBObject doc = new BasicDBObject( "name", "Matt" );
collection.insert( doc );
ObjectId id = (ObjectId)doc.get( "_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();
}

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:

collection.insert(doc);
ObjectId id = doc.getObjectId("_id");

Tags:

Java

Mongodb