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

JavaMongodb

Java Problem Overview


Is there an easy way to get the ID (ObjectID) of the last inserted document of a mongoDB instance using the Java driver?

Java Solutions


Solution 1 - Java

I just realized you can do this:

BasicDBObject doc = new BasicDBObject( "name", "Matt" );
collection.insert( doc );
ObjectId id = (ObjectId)doc.get( "_id" );

Solution 2 - Java

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");

Solution 3 - Java

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();
}

Solution 4 - Java

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)

Solution 5 - Java

After a document is inserted into the MongoDB collection, the successful insertion should update required fields (viz. _id). You may query the inserted object for the _id.

Solution 6 - Java

In MongoTemplate.class has a method

protected <T> void doInsert(String collectionName, T objectToSave, MongoWriter<T> writer) {

	assertUpdateableIdIfNotSet(objectToSave);

	initializeVersionProperty(objectToSave);

	maybeEmitEvent(new BeforeConvertEvent<T>(objectToSave, collectionName));

	DBObject dbDoc = toDbObject(objectToSave, writer);

	maybeEmitEvent(new BeforeSaveEvent<T>(objectToSave, dbDoc, collectionName));
	Object id = insertDBObject(collectionName, dbDoc, objectToSave.getClass());

	populateIdIfNecessary(objectToSave, id);
	maybeEmitEvent(new AfterSaveEvent<T>(objectToSave, dbDoc, collectionName));
}

and the method will set id for us

protected void populateIdIfNecessary(Object savedObject, Object id) {

	if (id == null) {
		return;
	}

	if (savedObject instanceof BasicDBObject) {
		DBObject dbObject = (DBObject) savedObject;
		dbObject.put(ID_FIELD, id);
		return;
	}

	MongoPersistentProperty idProp = getIdPropertyFor(savedObject.getClass());

	if (idProp == null) {
		return;
	}

	ConversionService conversionService = mongoConverter.getConversionService();
	MongoPersistentEntity<?> entity = mappingContext.getPersistentEntity(savedObject.getClass());
	PersistentPropertyAccessor accessor = entity.getPropertyAccessor(savedObject);

	if (accessor.getProperty(idProp) != null) {
		return;
	}

	new ConvertingPropertyAccessor(accessor, conversionService).setProperty(idProp, id);
}

we can see if the entity is a sub-class of BasicDBObject,it will set a id for us.

Solution 7 - Java

I think the answer to this is "No".

What you can do is provide your the _id yourself, either manually, or implement the CollectibleCodec mechanism (which is exactly what BasicBDDocument does). However all these solutions involve generating the ID clientside.

Having said that, I don't think there's any problem with generating the _id clientside.

Solution 8 - Java

This is insert operation:

DBCollection table1 = db.getCollection("Collection name");
BasicDBObject document = new BasicDBObject();
document.put("_id",value);		
document.put("Name", name);
table1.insert(document);

After insert u get last inserted id:

DBCollection tableDetails = db.getCollection("collection name");
BasicDBObject queryDetails = new BasicDBObject();
queryDetails.put("_id", value);
DBCursor cursorDetails =tableDetails.find(queryDetails);
DBObject oneDetails;
oneDetails=cursorDetails.next();		
String data=oneDetails.get("_id").toString();
System.out.println(data);

after getting value convert to inter type.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatt WView Question on Stackoverflow
Solution 1 - JavaMatt WView Answer on Stackoverflow
Solution 2 - JavaJadiel de ArmasView Answer on Stackoverflow
Solution 3 - JavazlobView Answer on Stackoverflow
Solution 4 - JavachxView Answer on Stackoverflow
Solution 5 - JavaRameshView Answer on Stackoverflow
Solution 6 - JavaZ.BillyView Answer on Stackoverflow
Solution 7 - JavaMatthewView Answer on Stackoverflow
Solution 8 - Javauser27View Answer on Stackoverflow