user8427401
user8427401

Reputation:

Get the object id after inserting the mongodb document in java

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

Upvotes: 2

Views: 3217

Answers (1)

Abhijit Sarkar
Abhijit Sarkar

Reputation: 24518

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.

Upvotes: 1

Related Questions