Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query the latest inserted item with Morphia

Tags:

morphia

How to query the latest inserted item in with Morphia And how to get the size of a collection?

like image 858
RandyTek Avatar asked Sep 15 '25 13:09

RandyTek


2 Answers

It depends what you mean by latest, but if you have a Date field with the creation date then you would do this:

T latest = ds.find().sort("-dateCreated").get();

And this would get you the count:

int count = ds.getCount(Class.class);

like image 84
Scott Hernandez Avatar answered Sep 18 '25 08:09

Scott Hernandez


When you save a document, the find method returns a object Key. If you want to know your object with the key that morphia insert in database, just get the key and put in the object parameter. I'm doing this way in my application.

To sort can you just pass .sort("dateCreated") to sort in ASC, or .sort("-dateCreated") that sort for the DSC way.

like image 22
Raduan Santos Avatar answered Sep 18 '25 10:09

Raduan Santos