RealmSwift - date range query on ObjectId possible?

Hello all,

the MongoDB ObjectID contains a whole lot of information. One of them is the timestamp at which the ObjectId was created.

On the Atlas collection, I am able to query those object ids for a date range. The trick seems to be to create two dummy object ids and pass the desired fromDate and toDate in the constructor.

Example:

let fromDateId = ObjectId((new Date(‘2022/1/01’), …)
let toDateId = ObjectId((new Date(‘2022/3/01’), …)

Then I can simply do a …

db.user.find({_id:{$gt: idMin, $lt: idMax}})

… to return me all users that were created in the first 2 months of 2022.

On RealmSwift I can create dummy objectIDs and pass a date like so:

let fromObjId = ObjectId(timestamp: fromDate, machineId: 0, processId: 0)
let toObjId = ObjectId(timestamp: fromDate, machineId: 0, processId: 0)

… however it seems like I can’t run a query like this:

users.filter("_id BETWEEN {%@, %@}", fromObjId, toObjId)

… as I get the error " ‘Invalid operator type’, reason: ‘Operator ‘BETWEEN’ not supported for type ‘object id’’". The same error applies to <= >=.

It would be odd if object id date queries would be supported on Atlas, but not within RealmSwift. Am I doing this wrong or does that simply not work? Obviously I could add a createdDate field to my documents to store the creation timestamp … but it seems a bit redundant given that the information is already in the object id.

Thank you for reading this - stay safe everyone.

Steve