generate ObjectId in rust mongo - mongodb

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

Related

MongoDb and F#: How to select distinct values?

I'm using the latest (at the time of writing) version (2.8) of the C# MongoDb driver.
I am using it from F#.
I want to select the distinct values of a field in a collection.
From this old question, the following does not work:
let client = new MongoClient(connString)
let db = client.GetDatabase("AirQuality")
let col = db.GetCollection<ReadingValue>("ReadingValue")
let res = col.DistinctAsync<string>("SensorName","{}")
The type string is not compatible with the type FieldDefinition<ReadingValue,string>.
From this answer, the following does not work either
let fd : FieldDefinition<ReadingValue, string> = "" :> FieldDefinition<ReadingValue, string>
In C# you can implicitly convert from string to FieldDefinition<T> (class implements implicit operator). Since types conversion works in a different way in F# you can use StringFieldDefinitionClass
let field = new StringFieldDefinition<ReadingValue, string>("SensorName")
let result = col.Distinct<string>(field, Builders<ReadingValue>.Filter.Empty)

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"
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)

Why the fatal error: Array index out of range show when print array in Swift?

I am new in Swift. I create a node swift file to store the node information. And the other group swift file is a group which store the all node.
The code of Node.swift is like the following:
class Node {
var id:UInt8=0
var type:Int=0
var name:String=""
var bdAddr:NSUUID!
//The node private packet counter
var nodePktNum:Int=0
}
The code of Group.swift is like the following:
class Group {
var mLedDevice:[LedDevice]? = [LedDevice]()
class LedDevice {
var node :Node?
var rssi :Int?
}
func allocateNode()
{
print("mLedDevice![0].node = \(mLedDevice![0].node))")
}
}
When I try call function (allocateNode) and try to print mLedDevice![0].node) via print("mLedDevice![0].node = \(mLedDevice![0].node))")
It show the error fatal error: Array index out of range.
Did I missing something for initialize of var mLedDevice:[LedDevice]? = [LedDevice]() ?
Thanks in advance.
===================================EDIT=================================
I want to add the item into array , so I create a parameter like let let leddevice : LedDevice , and try to give it some value. And add the leddevice into array mLedDevice. But it show constant 'leddevice' used before being initialized.
How to give the init value for let leddevice : LedDevice ?
func allocateNode()
{
let leddevice : LedDevice
leddevice.node?.id = UInt8(0)
leddevice.node!.bdAddr = NodeUUID
mLedDevice?.append(leddevice)
}
The only thing I can think about that can cause this is that the array is empty i.e. you are attempting to access index 0 of that array but that doesn't exist.
Try the following and it may give you an insight on how to solve it after seeing the content of the array:
print("mLedDevice = \(mLedDevice))")
In other words you are instantiating an array with no elements in it.
In your line of code
var mLedDevice:[LedDevice]? = [LedDevice]()
You are only initializing an empty array. What you are trying afterwards is to access the first element, of an empty array, which is out of bounds.
Before your print statement, you will need to add an item to your array
var ledDevice = LedDevice()
mLedDevice.append(ledDevice)
And then your print statement would not give you any errors.
UPDATED: Answer for the added question
let leddevice : LedDevice is defining a constant of type LedDevice but is not yet initialized, and then it is being used in the next lines of code. You should replace it with
let leddevice = LedDevice()
Which will also initialize the variable.
Note: If you have any further questions, you should write a new question for that.
Note2: Have you read any guides about initialization?

How to address key of retrieved object, in Realm, Swift?

I have created DB for my iOS mobile app using Realm, writing with Swift.
I am trying to find way to look up for matching username and password in DB
This is what I have currently, Attempting filtering and get an object with matching username
I am trying to address attribute/key called password from retrieved object
#IBAction func SignInCheck(sender: AnyObject) {
let realm = try! Realm()
var currentlogin = realm.objects(UserRecords).filter("name = LogUsernameTextField.text")
//this line causes SIGABRT to be thrown
if currentlogin.password == LogPasswordTextField.text { //This is the incorrectly addressed line
....
}
}
The issue maybe that I am not understanding how objects work in the right way, nor knowing the right syntax to address what I want.
I suspect it is in form of Result but I am still unable to find way to address desired information.
Here is the table structure for your information
class UserRecords: Object {
dynamic var username: String = ""
dynamic var password: String = ""
dynamic var latitude: Float = 0
dynamic var longtitude: Float = 0
}
I am open for suggestions better solution and ways of looking up/matching passwords in the table too, if any.
Thanks in advance
You are using a property called name in your filter string but in your UserRecords class the property is called username. Also you have to create the filter string differently:
var currentlogin = realm.objects(UserRecords).filter("username = '\(LogUsernameTextField.text!)'")
Also be aware that the filter method returns a list of UserRecord objects that match the filter and not a single object. So calling if currentlogin.password == ... will cause an error.
The list only has 1 item (because the username is unique) but it is still a list. So to access the UserRecord object you can call first:
var currentlogin = realm.objects(UserRecords).filter("name = LogUsernameTextField.text!").first
Also the text property of UITextField returns an Optional, so you have to unwrap it.

Dictionary Values in Swift

I am trying to access values I've set in a Swift dictionary. The dictionary has a String for the keys and values. My intent is to use the dictionary to set a string variable as I work through a series of URLs. In Objective-C I understand how this works. I have a string property called currentFeed that I pass the value of the dictionary to.
self.currentFeed = [NSString stringWithString: [self.URLDictionary objectForKey: #"FLO Cycling"]];
In Swift I am having a difficult time with this. I tried the following code and receive an error message.
self.currentFeed = self.URLDictionary["FLO Cycling"]
Error Message: "Cannot subscript a value of type '[String:String]' with an index of type 'String'.
For reference the dictionary was created in Swift in the following way. The constants were created with lets.
let kFLOCyclingURL = "http://flocycling.blogspot.com/feeds/posts/default?alt=rss"
let kTriathleteURL = "http://triathlon.competitor.com/feed"
let kVeloNewsURL = "http://velonews.competitor.com/feed"
let kCyclingNewsURL = "http://feeds.feedburner.com/cyclingnews/news?format=xml"
let kRoadBikeActionURL = "http://www.roadbikeaction.com/news/rss.aspx"
let kIronmanURL = "http://feeds.ironman.com/ironman/topstories"
The items were added to the dictionary with keys.
let URLTempDictionary = ["FLO Cycling" : kFLOCyclingURL, "Triathlete" : kTriathleteURL, "Velo News" : kVeloNewsURL, "Cycling News" : kCyclingNewsURL, "Road Bike Action" : kRoadBikeActionURL, "Ironman" : kIronmanURL]
Thanks for any help.
Take care,
Jon
This compiles fine for me. The only thing I noticed was that your dictionary is named URLTempDictionary and you're accessing URLDictionary. :)
Option a (safest, most robust)
if let dict = self.URLDictionary
{
self.currentFeed = dict["FLO Cycling"]
}
Option b (use with caution, possible runtime error)
self.currentFeed = dict!["FLO Cycling"]