Docs Menu

Sort Queries - Kotlin SDK

To sort results, specify a sort in the query passed to realm.query() with the SORT keyword. Similarly, use DISTINCT to constrain results to unique values of a field, and LIMIT to cap the number of results. The SDK provides convenience methods on RealmQuery so you don't have to manually write the keywords:

When used on the same query in both RQL and method form, SORT, DISTINCT, and LIMIT execute in the order they're added to the query. This can impact the results returned from your query.

// sort in descending order, frogs with distinct owners, only the first 5, with convenience methods
val convenientlyOrganizedFrogs: Flow<ResultsChange<Frog>> =
realm.query<Frog>("name = 'George Washington'")
.sort("age", Sort.DESCENDING).distinct("owner").limit(5).asFlow()
val asyncCallConvenience: Deferred<Unit> = async {
convenientlyOrganizedFrogs.collect { results ->
when (results) {
// print out initial results
is InitialResults<Frog> -> {
for (frog in results.list) {
Log.v("Frog: $frog")
}
} else -> {
// do nothing on changes
}
}
}
}
// sort in descending order, frogs with distinct owners, only the first 5, using RQL
val somewhatLessConvenientlyOrganizedFrogs: Flow<ResultsChange<Frog>> =
realm.query<Frog>("name = 'George Washington' SORT(age DESC) DISTINCT(owner) LIMIT(5)").asFlow()
val asyncCallLessConvenient: Deferred<Unit> = async {
somewhatLessConvenientlyOrganizedFrogs.collect { results ->
when (results) {
// print out initial results
is InitialResults<Frog> -> {
for (frog in results.list) {
Log.v("Frog: $frog")
}
} else -> {
// do nothing on changes
}
}
}
}
Note

find() runs a synchronous query on the thread it is called from. As a result, avoid using find() on the UI thread or in logic that could delay the UI thread. Prefer asFlow() in time sensitive environments.

←  Find Objects of a Type - Kotlin SDKIteration - Kotlin SDK →
Give Feedback
© 2022 MongoDB, Inc.

About

  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2022 MongoDB, Inc.