mongodbswift3mongokitten

How to query a value stored as UInt64 from mongodb?


I am using mongokitten as interface between my osx app and mongodb.I store date as UInt64 into the db.In Db it is stored in this format - NumberLong("1514450415154").There is no issue when inserting and reading data from db since in both cases the value is simply 1514450415154.But when trying to query,just the value is not sufficient.Hence I'm not able to write the query.Can anyone help me find a possible solution?

I am using mongokitten major version:4, swift version:3,xcode 9.Yes I am using Codable to make use of the Encodable and Decodable protocols.

Sample code:

let dateUint : UInt64 = UInt64(date.timeIntervalSince1970 * 1000.0); let query : Query = Query(aqt: .greaterThanOrEqual(key: "super.upd_dtm", val: dateUint as! Primitive))

Structure stored in db:

"_id" : "093FF386-1D53-4DFC-AC56-D2B778C7D6FE", "super" : { "rel_ver" : "", "crt_in" : "macpro", "crt_by" : "ABC", "lst_syn" : NumberLong("1514875651306"), "is_drty" : false, "crt_dtm" : NumberLong("1514875651306"), "upd_dtm" : NumberLong("1514875651306"), "doc_ver" : NumberLong(0) }, "prj_nme" : "project1", "prj_id" : "4545C803-D41E-4A4F-9409-538FC183D8B3"


Solution

  • You'll need to provide a few more details regarding your requirements so I can properly answer your question.

    UInt64 isn't a standard MongoDB type, however Int64 and Int32 are. MongoKitten will try to convert an UInt64 to a numberlong (Int64) in the codable APIs. In the non-codable APIs you quite explicitly need to convert the UInt64 to a BSON supported primitive type, yourself


    You can use a normal Int in your query. Since (almost) all devices/servers running Swift will be 64-bits, MongoKitten doesn't support 32-bits (although it might work). That means an Int is the same as Int64. If you store your dates inside MongoDb as a Date rather than an epoch integer you'll also be able to use Foundation.Date within MongoKitten, including for Queries.

    let epoch = date.timeIntervalSince1970 * 1000.0)
    let results = try collection.find("super.upd_dtm" >= epoch)