Home > Enterprise >  Fetch a random record from a Realm database (Swift)
Fetch a random record from a Realm database (Swift)

Time:12-30

I am trying to fetch a random record from my Swift Realm database.

I have previously used the sample function in mongoDB, so I thought there must be an equivalent in Realm (it's based on mongoDB, right?)

I can't find any documentation on such a function, and I've only found search results which suggest to fetch the entire collection then choose a random record [1, 2]. Obviously, this is inefficient.

Am I missing something obvious, is there a better way to do it?

See below for an example mongoDB query:

db.Words.aggregate([
{ $match: { gender: gender } },
{ $sample: { size: 1 } }
])

CodePudding user response:

For clarity the code in the question is not part of the Realm Swift SDK for local or sync but it is a query directly to Atlas using app services, so it would be valid for non-sync'ing or non-local applications. (Use the Swift SDK if possible!)

If we're doing this using the SDK, you can actually leverage high-level Swift functions to return a result using .randomElement()

So given a PersonClass that has a name property

class PersonClass: Object {
   @Persisted var name = ""
}

we can this use this code to return a random person from Realm and output their name to console

if let randomPerson = realm.objects(PersonClass.self).randomElement() {
    print(randomPerson.name)
} else {
    print("no data was returned)")
}
  • Related