mongoDB 获取最后插入的文档的ObjectID/_id方法

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
http://stackoverflow.com/questions/7720256/mongodb-getting-objectid-of-last-inserted-document-with-multiple-concurrent-wr

你可能感兴趣的:(mongoDB 获取最后插入的文档的ObjectID/_id方法)