获取 mongoDB w/Java 驱动程序中最后插入的文档的 ID

有没有一种简单的方法可以使用 Java 驱动程序获得 mongoDB 实例最后插入的文档的 ID (ObjectID) ?

60243 次浏览

I just realized you can do this:

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

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)

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.

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

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.

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

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.

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.