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" );
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");
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();
}
I do not know about the Java driver but for posterity, the getLastError command can be run to get the _id of a write, even an upsert (as of 1.5.4)