Swift: Conditionally build find query

I’m trying to build a query a piece at a time. I understand I could do something like the following, which I think I got from the documentation:

let queryFilter: BSONDocument = [
	"date_no_dash": [
		"$gte": BSON(integerLiteral: (year - buffer) * 10_000),
		"$lte": BSON(integerLiteral: ((year + buffer) * 10_000) - 1)
	]
]

But I need to do this in pieces, conditionally.

I’m trying to write a function that can build the date range subquery, then another function that can receive the field that it’s for and build the final BSONDocument. So…

	func mongoDateRangeSubQuery(oDateRange: CDateRange) -> BSON {
		var oRangeQuery: BSON = [:]
		if let oDate = oDateRange.oDate {
			oRangeQuery["$eq"] = BSON.datetime(oDate)
		}
		else {
			if let oDateFrom = oDateRange.oDateFrom {
				if oDateRange.bIsIncludedFrom! {
					oRangeQuery["$gte"] = BSON.datetime(oDateFrom)
				}
				else {
					oRangeQuery["$gt"] = BSON.datetime(oDateFrom)
				}
			}
			if let oDateTo = oDateRange.oDateTo {
				if oDateRange.bIsIncludedTo! {
					oRangeQuery["$lte"] = BSON.datetime(oDateTo)
				}
				else {
					oRangeQuery["$lt"] = BSON.datetime(oDateTo)
				}
			}
		}
		return oRangeQuery
	}

and the result of that would be passed into this:

	func mongoQuery(sOptionsFieldName: String, rangeSubquery: BSON) -> BSONDocument {
		let oQuery: BSONDocument = [
			sOptionsFieldName : rangeSubquery
		]
		return oQuery
	}

The problem is I get an error on each of the oRangeQuery[...] = BSON... lines: “Value of type ‘BSON’ has no subscripts”. I vaguely understand that error in general, but I can’t figure out what to do about it? How does one build a query conditionally like this?

(I can solve this by changing the BSON return type in that function to BSONDocument and then those errors go away but then I get "Cannot convert value of type ‘BSONDocument’ to expected dictionary value type ‘BSON’ (and I understand why that is)).

Is it possible to build a find query in multiple steps, and with conditions, like this, or can it only be done by assigning an entire dictionary literal at once?

If it makes any difference I’ve built very similar code (without the types of course) in javascript/node and it works like a charm. Need it working in Swift instead now. I’m only a week into Swift with MongoDB so please be gentle. :wink:

Thanks in advance for any help!