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>
Community
  • 1
  • 1
Alex
  • 7,007
  • 18
  • 69
  • 114

2 Answers2

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.
Rachit Ahuja
  • 371
  • 2
  • 15
  • 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. – Rachit Ahuja Jul 22 '15 at 22:50
  • @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. – Alex Jul 23 '15 at 14:06
  • 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. – Rachit Ahuja Jul 23 '15 at 14:08
  • This code is not compiled: FindIterable currentVersionDocumentIterable = coll.find(); currentVersionDocumentIterable.sort("name", 1).limit(50); – Alex Jul 23 '15 at 14:10
  • Try doing coll.find().sort("name",1).limit(50); – Rachit Ahuja Jul 23 '15 at 14:14
  • I have worked with many versions, I am using the current stable release 3.0.4, but this should work for all the versions. This is the correct format. db.collections.find().sort(key:value).limit(int value).skip(some int value); You can also refer to this article I found. http://stackoverflow.com/questions/4421207/mongodb-how-to-get-the-last-n-records – Rachit Ahuja Jul 23 '15 at 19:55
  • Also try this article: http://docs.mongodb.org/manual/reference/method/db.collection.find/ – Rachit Ahuja Jul 23 '15 at 20:01
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”

Alex
  • 7,007
  • 18
  • 69
  • 114