2

I am using mongodb 3.4 and I want to get the last inserted document id. I have searched all and I found out below code can be used if I used a BasicDBObject.

BasicDBObject docs = new BasicDBObject(doc);
collection.insertOne(docs);
ID = (ObjectId)doc.get( "_id" );

But the problem is am using Document type not BasicDBObject so I tried to get it as like this, doc.getObjectId();. But it asks a parameter which I actually I want, So does anyone know how to get it?

EDIT

This is the I am inserting it to mongo db.

Document doc =  new Document("jarFileName", jarDataObj.getJarFileName())
                                        .append("directory", jarDataObj.getPathData())
                                        .append("version", jarDataObj.getVersion())
                                        .append("artifactID", jarDataObj.getArtifactId())
                                        .append("groupID", jarDataObj.getGroupId());

If I use doc.toJson() it shows me whole document. is there a way to extract only _id?

This gives me only the value i want it like the objectkey, So I can use it as reference key.

collection.insertOne(doc);
jarID = doc.get( "_id" );
System.out.println(jarID); //59a4db1a6812d7430c3ef2a5
  • "Talk is cheap, show me the code". - Linus Torvalds. – Abhijit Sarkar Aug 29 '17 at 03:02
  • Both [`BasicDBObject`](http://api.mongodb.com/java/current/com/mongodb/BasicDBObject.html) and [`Document`](http://api.mongodb.com/java/current/org/bson/Document.html) implement the [`Map`](http://docs.oracle.com/javase/7/docs/api/java/util/Map.html?is-external=true) interface of which `.get()` actually belongs to. So all you need to is interchange `Document` for `BasicDBObject` in the above code. – Neil Lunn Aug 29 '17 at 03:07
  • https://stackoverflow.com/questions/3338999/get-id-of-last-inserted-document-in-a-mongodb-w-java-driver?rq=1 this can help – Viet Aug 29 '17 at 03:15
  • I edited the question, but I want the the objectid not the id value. –  Aug 29 '17 at 03:15
  • @Abhijit Sarkar posted the code you wanted, any ideas? –  Aug 29 '17 at 03:27

1 Answers1

1

Based on ObjectId Javadoc, you can simply instantiate an ObjectId from a 24 byte Hex string, which is what 59a4db1a6812d7430c3ef2a5 is if you use UTF-8 encoding. Why don't you just do new ObjectId("59a4db1a6812d7430c3ef2a5"), or new ObjectId("59a4db1a6812d7430c3ef2a5".getBytes(StandardCharsets.UTF_8))? Although, I'd say that exposing ObjectId outside the layer that integrates with Mongo is a design flaw.

Abhijit Sarkar
  • 21,927
  • 20
  • 110
  • 219