Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

mongodb

Is there an easy way to get the ID (ObjectID) of the last inserted document of a mongoDB instance using the Java driver?

like image 876
Matt W Avatar asked Jul 26 '10 21:07

Matt W


People also ask

How can I see last inserted record in MongoDB?

To get last inserted document, use sort() along with limit(1).

How do I get the latest file in MongoDB?

find(). sort({x:1}); The 1 will sort ascending (oldest to newest) and -1 will sort descending (newest to oldest.) If you use the auto created _id field it has a date embedded in it ... so you can use that to order by ...

What is document ID MongoDB?

Architecturally, by default the _id field is an ObjectID, one of MongoDB's BSON types. The ObjectID is the primary key for the stored document and is automatically generated when creating a new document in a collection.

How do I find the ID of a document in MongoDB?

When a new document is inserted into a MongoDB collection, chances are you won’t know its ID. If a value isn’t explicitly supplied for "_id", MongoDB will generate one upon insertion. Fortunately, it’s easy to retrieve the ID of the last inserted document with just a few lines of Java code.

How to get last inserted document in MongoDB?

MongoDB query to get last inserted document? MongoDB query to get last inserted document? To get last inserted document, use sort () along with limit (1).

How tobsondocument () works in MongoDB?

When I call ToBsonDocument (), the Id field gets populated with ObjectId which gets pushed to Mongo DB. It creates the Id itself in the code instead of delegating to Mongo DB to create it. But it suffices my case. Show activity on this post.

How to avoid casting from object to objectId in MongoDB?

– Stu_Dent Oct 11 '20 at 13:14 Add a comment | 15 To avoid casting from Objectto ObjectId, given a com.mongodb.client.MongoCollection collectionand a org.bson.Document doc, you can do the following: collection.insert(doc); ObjectId id = doc.getObjectId("_id"); Share Follow edited Aug 23 '16 at 18:23


1 Answers

I just realized you can do this:

BasicDBObject doc = new BasicDBObject( "name", "Matt" ); collection.insert( doc ); ObjectId id = (ObjectId)doc.get( "_id" ); 
like image 109
Matt W Avatar answered Sep 24 '22 06:09

Matt W