1

There is an analogous post for using mongodb scripting mongodb: how to get the last N records?

How to achieve the same goal with Java getting the last inserted collection document? Just in case, I am using the 3rd version of the mongodb Java driver, my mongodb dependencies in pom.xml are as follows:

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>3.0.2</version>
</dependency>   
<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>bson</artifactId>
    <version>3.0.2</version>
</dependency>

2 Answers 2

2

Use .limit()

db.foo.find().limit(50);

Or if you want to sort and then get last records then you can do

db.foo.find().sort({_id:1}).limit(50);  and -1 for descending.
Sign up to request clarification or add additional context in comments.

7 Comments

Its a java code, You can try doing MongoDatabase db = client.getDatabase("test"); db.collection.find().sort(new Document("x", 1)).limit(n); If you still face problems, you can put the code here. I hope this solves your problem.
@Rashit, Thank you. What do you mean by ("x", 1), is "x" any field in the document and what is 1 here? How to do "and -1 for descending", what is the code? By the way "db.foo.find().sort({_id:1}).limit(50)" is not compiled.
Yes x is any field. Yes just use -1 for descending in the same code format as above. Also please accept the answer. Thank you.
This code is not compiled: FindIterable<Document> currentVersionDocumentIterable = coll.find(); currentVersionDocumentIterable.sort("name", 1).limit(50);
Try doing coll.find().sort("name",1).limit(50);
|
1

It is the new syntax in MongoDB version 3, therefore I could not use the suggested answer . So the working code is as follows:

MongoCollection<Document> coll = db.getCollection(<collectionName>);

FindIterable<Document> currentVersionDocumentIterable =   
    coll.find().sort(new Document("_id", -1)).limit(50);

Inside sort one needs to insert “new Document”

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.