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

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

Add Comment


  • 3 Answer(s)

    You can do this one:

    BasicDBObject doc = new BasicDBObject( "name", "Matt" );
    collection.insert( doc );
    ObjectId id = (ObjectId)doc.get( "_id" );
    
    Answered on January 8, 2019.
    Add Comment

    The following code to solve your issue:

    doc.set("_id", new ObjectId())
    

    just try this

    if ( ensureID && id == null ){
    id = ObjectId.get();
    jo.put( "_id" , id );
    }
    public static ObjectId get(){
    return new ObjectId();
    }
    
    Answered on January 8, 2019.
    Add Comment

    The following code 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");
    
    
    Answered on January 8, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.