http://stackoverflow.com/questions/3338999/get-id-of-last-inserted-document-in-a-mongodb-w-java-driver
mongoDB api就可以实现,请仔细查看集合insert方法的源代码
a.文档插入后可以获取到插入的文档的ObjectID
代码:
BasicDBObject doc = new BasicDBObject( "name", "Matt" );
collection.insert( doc );
ObjectId id = (ObjectId)doc.get( "_id" );
b.文档插入之前,可以自己生成一个ObjectID,简单的方法如下
代码:
//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();
}
参看文章链接:
http://www.thebirdietoldme.com/userActions/thread/Question.aspx?id=3338999
时间: 2024-10-03 21:21:48