Querying MongoDB from Realm

I am trying to run an Atlas query via Realm using swift, code is as follows:

         app.login(credentials: Credentials.anonymous) { results in

                switch results {
                case .failure(let error):
                    print("Login failed: \(error.localizedDescription)")
                case .success(let user):
                    print("Successfully logged in as user \(user)")

                    let client = self.app.currentUser!.mongoClient("mongodb-atlas")
                    let database = client.database(named: "Incidents")
                    let collection = database.collection(withName: "Incidents")

                    let qf: Document = ["incidentDetails.lastUpdated":"{$gt:ISODate('2022-07-23')}"]

                    collection.find(filter: qf) { result in
                        switch result {
                        case .failure(let error):
                            print("Login failed: \(error.localizedDescription)")

                        case .success(let documents):
                            print("Great Success")
                            for doc in documents {
                                print("Title: \(doc)")
                            }

                        }
                    }
                }

            }

This executes successfully, logs an anon. user in runs the query returning success, however I get no documents back. I assume at this point it is because of my filter document

let qf: Document = ["incidentDetails.lastUpdated":"{$gt:ISODate('2022-07-23')}"]

But I am at a loss as to how to write this in Swift. Essentially, I only want to return documents updated within the last few days. I can run this via Atlas using

{"incidentDetails.lastUpdated": { $gt:ISODate('2022-07-23')}}

Any help would be appreciated

I should have, I’ve tried various versions of the filter document, with and without {} as well as placing them in different places

Some basic troubleshooting may help clarify the issue.

I assume the object you are querying for has other properties. Try to just read that object via another property with a known value and see if you get a result. If not, there’s a setup or config issue. If so, then the query in the question is malformed.

Try something like this

let qf: Document = ["some_property": "some_known_value"]
collection.findOneDocument(filter: qf) { result in

Also… isn’t the Date done line this new Date("<YYYY-mm-dd>") which returns an ISODate or use the date format ISODate("2022-07-23T 09:10:24.000Z"

Report back your findings.

Hi Jay,

This is the object:

Screenshot 2022-07-26 at 19.01.38

If I use let qf: Document = [“incidentDetails.incidentType”:“Small”] Then it returns 20 documents as expected.

In terms of the right format for the date, I am not sure. Various forms work in Atlas:

{“incidentDetails.incidentType”: {$gt:‘2022-07-26’}}
{“incidentDetails.incidentType”: {$gt:Date(‘2022-07-26’)}}
{“incidentDetails.incidentType”: {$gt:“2022-07-26”}}

I just cannot get an equivalent working from RealmSwift

The code in the initial question looks pretty close - did you try

let qf: Document = ["incidentDetails.lastUpdated": "{$gt: new Date('2022-07-23')}"]

Thanks, I thought it looked close too, but no dice: using your code it finds zero documents, if I change to a non-date field 705:

Screenshot 2022-07-26 at 20.09.29

could it be that MongoDB via realm doesn’t support $gt ?

Well, that’s frustrating. I am pretty sure $gt is supported as it’s defined in the manual.

How is the actual date property defined on the object? Is it an ISODate()?

It is indeed frustrating :slight_smile:

This is in the app logs of Realm:

{
  "name": "find",
  "arguments": [
    {
      "database": "Incidents",
      "collection": "Incidents",
      "query": {
        "incidentDetails.lastUpdated": {
          "$gt": "Date('2022-07-26')"
        }
      }
    }
  ],
  "service": "mongodb-atlas"
}

Annoyingly, if I take the query text and run it in Atlas, I get results, I’ve even tried nesting documents:

let qf: Document = ["incidentDetails.lastUpdated": ["$gt":"Date('2022-07-23')"]]

The field is a Date:

Resolved at last!!

let maxDate = Date(timeIntervalSinceNow: -3 * 24 * 3600)
let qf: Document = ["incidentDetails.lastUpdated":["$gt": .datetime(maxDate)]]

This returns the correct documents

2 Likes

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