Java MongoDB FindOne to get last inserted record

For anyone who is looking for a more recent answer:

Here's how you finding the last inserted element by "_id" with mongodb-driver in your Java project.

// connect to your collection. 
MongoCollection<Document> collection = database.getCollection("yourCollection");

//request last inserted doc
Document myDoc = collection.find().sort(new Document("_id", -1)).first();

Hope this helps!


To be clear, natural order is not insertion order, except in the case of capped collections. You will need another criteria to sort by.

Assuming you are using the default ObjectID, you can use this as a metric for insertion as the default value starts with the insertion time (to the millisecond) and is always unique.

You should also use a find, rather than a findOne. Try the following:

db.market.find({}).sort({_id:-1}).limit(1)

if you want to do it in your JAVA code you cand do like this

Document myDoc = (Document)collection.find().sort(new BasicDBObject(<field>,-1)).first();

it will return a document the is the last inserted ordered by that significant field =)

Tags:

Java

Mongodb