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