Having difficulty filtering a collection

Hi, I wanted to kick the tires on the mongodb driver in swift. I am making a simple mac application and I can’t seem to query the database.

I tried following the code examples in the documentation, but they seem to be a bit out of date.

I have tried the following code, but get a compiler error on the collection.find line. “Type of expression is ambiguous without more context”

import MongoSwiftSync
...

    func test() {
        
        // my holidays collection has a bunch of entries like:
        // _id: 639dacae733952abc2be7c8e
        // date_no_dash: 20220101
        // holiday: "New Year's Day"
        
        struct holiday: Codable {
            let _id: BSONObjectID
            let date_no_dash: Int
            let holiday: String
        }
        
        let year = 2022 // the year to query holidays for
        let buffer = 2  // the amount of years to buffer on either side
        
        let collection = mongoDB.collection("holidays", withType: holiday.self)
        
        let queryFilter: BSONDocument = [
            "date_no_dash": [
                "$gte": BSON((year - buffer) * 10_000),
                "$lte": BSON(((year + buffer) * 10_000) - 1)
            ]
        ]
        
        do {
            let tmp = try collection.find(queryFilter) { result in
                switch result {
                case .failure(let error):
                    print("error:\(error)")
                case .success(let documents):
                    for doc in documents {
                        print("document \(doc)")
                    }
                }
            }
        } catch {
            print("Error trying to find on collection: \(error)")
        }
        
    }

I am also not sure if the queryFilter will work as I intend. But in general I find the result fetching with a switch statement fairly cumbersome. Isn’t there a more simple way?
Thanks

Hi @Joseph,

Thank you for getting in touch. The documentation examples you link to are for the Realm Swift SDK, not the MongoDB Swift driver.

To iterate through the results in the Swift driver, the code would look like this:

for result in try collection.find(queryFilter) {
    switch result {
    case .success(let doc):
        print(doc)
    case .failure(let error):
        print("error: \(error)")
    }
}

In general, to avoid a switch statement on a Result, you can call .get() instead, like:

for result in try collection.find(queryFilter) {
    print(try result.get())
}

See the docs for Result.get() here. This method will either return the contained value on success, or throw the contained error on failure.