Is there an easy way to get the ID (ObjectID) of the last inserted document of a mongoDB instance using the Java driver?
To get last inserted document, use sort() along with limit(1).
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 ...
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.
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.
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).
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.
– 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
I just realized you can do this:
BasicDBObject doc = new BasicDBObject( "name", "Matt" ); collection.insert( doc ); ObjectId id = (ObjectId)doc.get( "_id" );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With