How to query a value stored as UInt64 from mongodb? - 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"

You'll need to provide a few more details regarding your requirements so I can properly answer your question.
Which MongoKitten version are you using?
Which Swift version are you using?
Are you using codable?
Can you post some code that reproduces the problem?
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)

Related

How to convert a MongoDB RawDocumentBuf to a Rust struct?

I am trying to use MongoDB rust driver with Rayon to make it faster.
I know how to convert a RawDocumentBuf into a Document like this, which works really fast.
let docs: Vec<RawDocumentBuf> = coll.find(None, None).await?.try_collect::<Vec<_>>().await?;
let _y: Vec<Document> = docs.par_iter().map(|x| x.to_document().unwrap()).collect();
But I want a Rust struct, say Book, eventually.
A Document can be converted into a struct, but I am not sure how to get a struct in the closure above.
let book: Book = bson::from_bson(Bson::Document(doc));
You just missed another unwrap() after from_bson() at the end.
However you don't have to go via Document, you can deserialize from a RawDocumentBuf via bson::from_slice():
let docs: Vec<RawDocumentBuf> = coll.find(None, None).await?.try_collect().await?;
let books: Vec<Book> = docs
.par_iter()
.map(|raw| bson::from_slice(raw.as_bytes()).unwrap())
.collect();

Epoch to Date during the decode

I have the following json object.
{"date" : 1596304900, "name" : "registration"}
I have the following struct
struct Classroom : Codable{
let date : Int
let name : String
}
As you see in the json object, date is actually epoch time and want to convert it to human readable date during the decode operation. I wonder how it needs to be done during the decode.
Make your date a Date instead of an Int, and use a JSONDecoder with its date decoding strategy set to the epoch decoder:
https://developer.apple.com/documentation/foundation/jsondecoder/datedecodingstrategy/secondssince1970
Everything will happen correctly as if by magic. (In the example you've given, the date will turn out to be August 1, 2020, at 18:01:40 GMT.)
Note that this will not be "human-readable"; it will be a date. You don't store human-readable; you show human readable. You deal with that in the interface only, with a formatter.

How can I convert a String to a Dictionary type in Swift?

I have a String
example:
"['name': 'consumer_nam', 'date': 'date']"
I want to convert this to a dictionary type in Swift4.
Dictionaries in Swift can be represented by [String : Any], and many other ways.
let dictionary : [String : Any] = ["name" : "consumer_nam", "date" : "date"]
If what you're trying to do is parse the String, you can take a look here and here.
It looks like your String is supposed to be interpreted as a Dictionary. It looks a bit like a textual representation of JSON.
Find a spec for the exact format of that String, and then you write code to parse it.
It may be easier to convince whoever produced that string to produce for example a JSON document instead (which would be stored as Data, not String).

generate ObjectId in rust mongo

i'm trying to convert String _id to a ObjectId object, what i'm already try :
use mongodb::{Bson, bson, doc};
Bson::ObjectId(str) // failed to resolve
bson::Bson::String // undeclared /& private
library : mongo-rust-driver-prototype
using mongodb 2.2
use std::str::FromStr;
...
let id = mongodb::bson::oid::ObjectId::from_str("id_str").unwrap();
Try this way
let mongo_id = str.get_object_id("_id").unwrap();
let mongo_id_hex = mongo_id.to_hex();
For more info please check this link
Generate ObjectId Object from string :
mongodb::oid::ObjectId::with_string(&"").unwrap() // change &"" with var or static value
References :
https://docs.rs/mongodb/0.3.12/mongodb/?search=object
https://docs.rs/mongodb/0.3.12/mongodb/oid/struct.ObjectId.html#method.with_string

Contextual type 'AnyObject' cannot be used with dictionary literal multi level dictionary

I'm running into an issue with creating a multi-level dictionary in Swift and have followed some of the suggestions presented here:
var userDict:[String:AnyObject]? = ["SystemId": "TestCompany",
"UserDetails" : ["firstName": userDetail.name, "userAddress" : "addressLine1" userDetail.userAdd1]]
The use of [String:AnyObject]? works for the first level of the Dict, but Swift is throwing the same error at the next level Dict, UserDetail[]. Any suggestions would be greatly appreciated
I'm not pretty sure what are the types of userDetail.name and userDetail.userAdd1 but if they are Strings you should let it [String:String]?
However, [String:Any]? should solve your problem. If you are sure that you want to let it [String:AnyObject]? (I don't think that you want to), you can do something like this:
var userDict:[String:AnyObject]? = ["SystemId": "TestCompany" as AnyObject,
"UserDetails" : ["firstName": userDetail.name, "userAddress" : userDetail.userAdd1] as AnyObject]
Hope this helped.