How to query by ISODate?


Am going through the docs for the swift sync driver, and am trying to find details on how to query by an ISODate. Is this conforming to ISO8601 by chance?


Hi Mark,

Are you using the MongoDB Swift driver or the MongoDB Realm Swift SDK? If using the Realm SDK, are querying the local Realm database?


I’m using the MongoDB Swift Sync Driver (linux) - not using Realm.


Hi Mark, thanks for reaching out.

By ISODate, maybe you are referring to ISODate in the MongoDB shell? That is a convenience helper for creating a new MongoDB datetime. The database itself stores dates as signed 64-bit integers representing the number of milliseconds since the Unix epoch.

The MongoDB drivers, Swift included, typically have facilities for converting native date types in each language to/from that format the database uses. In the Swift driver case, the relevant type is Date: Apple Developer Documentation

If you want to insert or query with a Swift Date object you can do something like the following:

// create some reference dates
let now = Date()
let yesterday = Date(timeIntervalSinceNow: -1 * 24 * 60 * 60)
let twelveHoursAgo = Date(timeIntervalSinceNow: -1 * 12 * 60 * 60)

// insert some data with various date values
try collection.insertMany([
    ["_id": 1, "d": .datetime(yesterday)],
    ["_id": 2, "d": .datetime(yesterday)],
    ["_id": 3, "d": .datetime(now)],
    ["_id": 4, "d": .datetime(now)]

// queries with exact dates
let nowDocs = try collection.find(["d": .datetime(now)])
print(try Array(nowDocs).map { try $0.get() } )

let yesterdayDocs = try collection.find(["d": .datetime(yesterday)])
print(try Array(yesterdayDocs).map { try $0.get() } ) 

// query with a range
et recentDocs = try collection.find(["d": ["$gt": .datetime(twelveHoursAgo)]])
print(try Array(recentDocs).map { try $0.get() } )

This will print:

[{"d":{"$date":"2021-06-16T19:01:24.337Z"},"_id":3}, {"_id":4,"d":{"$date":"2021-06-16T19:01:24.337Z"}}]
[{"_id":1,"d":{"$date":"2021-06-15T19:01:24.337Z"}}, {"_id":2,"d":{"$date":"2021-06-15T19:01:24.337Z"}}]
[{"d":{"$date":"2021-06-16T19:01:24.337Z"},"_id":3}, {"d":{"$date":"2021-06-16T19:01:24.337Z"},"_id":4}]

If you need to convert to/from ISO-8601 formatted date strings and Swift Dates I would suggest looking into DateFormatter: Apple Developer Documentation

Let me know if that answers your question or if you need more information!


1 Like

Hi Kaitlin,

As always, your answers are incredibly detailed and helpful. Everything is working. That ISODate in the shell was leading me down the wrong path.


1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.