Reputation: 3387
I am using Realm DB
in my Android app and I want to fetch for just one item with the most recent timestamp. I couldn't achieve it because I don't know what to do. But, this is what I'm doing
TopicModel topicModel = realm.where(TopicModel.class).equalTo("rootMessageId", getRootMessageId()).findFirst();
List<MessageModel> messageModel = realm.where(MessageModel.class)
.equalTo("theMainTopidId", topicModel.getRadomUdid())
.findAllSorted("updatedTime", Sort.DESCENDING);
Log.e(TAG, "Recent Message: " + messageModel.get(messageModel.size() - 1).getUpdatedTime());
Upvotes: 1
Views: 845
Reputation: 43314
I don't think you can get exactly the same implementation as you describe for mongodb. Sorting results is something you do at the end of or after a query.
However, the RealmResults you get after calling findAll for example is a very low memory consuming list of references. The results you get from a query are not copied objects, they are just references. See also the class description of RealmResults:
This class holds all the matches of a RealmQuery for a given Realm. The objects are not copied from the Realm to the RealmResults list, but are just referenced from the RealmResult instead. This saves memory and increases speed.
So it shouldn't really matter. And if you just want to find the most recent message, you could do this one-liner instead:
MessageModel mm = realm.where(MessageModel.class)
.equalTo("theMainTopidId", topicModel.getRadomUdid())
.findAllSorted("updatedTime", Sort.DESCENDING)
.where()
.findFirst();
Upvotes: 3