How can I convert an AnyBson document to a Realm Swift Object

I’m developing an SwiftUI app (with Realm) to help people find specific places. On this app I have a search bar so people can type some keywords to find these places.

My goal is to use Atlas Seach with Realm. After investigation I found a way, using Realm Functions. So I developed this function (SearchRealm):

exports = function(typpedText){
    Function to get places according to typpedText
    const places =
    let arg = typpedText
    let found = places.aggregate([
        $search: {
            index: 'placeIndex',
            text: {
                query: arg,
                    path: {
                        'wildcard': '*'
    return {result : found};

and on Xcode I did this :

Task {
    do {
         // calling SearchRealm function
         let results = try await user.functions.SearchRealm([AnyBSON(searchValue)])
         print("found places : \(results)")
    } catch {
        print("Function call failed: \(error.localizedDescription)")

My problem is “results” is an “AnyBson” type. How can I convert it to my Swift Realm Object “Place” ?

Thank You.

1 Like

Did you figure this out? I’m facing the same challenge

1 Like

For now I just find a temporary solution returning only a list of ObjectIds in the Realm Function with :

    { $project: { title: 1, score: { $meta: "searchScore" }}},
    { $limit: 10 }

and on Xcode I filter my Realm Objects with :

objects(Place.self).filter("_id IN %@", arrayPlaceId)

it works, I don’t know if it the best way to filter data