How to convert objectid to string - pymongo

I want to get the string character from an ObjectId object. I use pymongo.
eg: ObjectId("543b591d91b9e510a06a42e2"), I want to get "543b591d91b9e510a06a42e2".
I see the doc, It says ObjectId.toString(), ObjectId.valueOf().
So I make this code: from bson.objectid import ObjectId.
But when I use ObjectId.valueOf(), It shows:
'ObjectId' object has no attribute 'valueOf'.
How can I get it? Thanks.

ObjectId.toString() and ObjectId.valueOf() are in Mongo JavaScript API.
In Python API (with PyMongo) proper way is to use pythonic str(object_id) as you suggested in comment, see documentation on ObjectId.

ObjectId.toString() returns the string representation of the ObjectId() object.
In pymongo str(o) get a hex encoded version of ObjectId o.
Check this link.

What works for me is to "sanitize" the output so Pydantic doesn't get indigestion from an _id that is of type ObjectId...here's what works for me...
I'm converting _id to a string before returning the output...
# Get One
#router.get("/{id}")
def get_one(id):
query = {"_id": ObjectId(id)}
resp = db.my_collection.find_one(query)
if resp:
resp['_id'] = str(resp['_id'])
return resp
else:
raise HTTPException(status_code=404, detail=f"Unable to retrieve record")

Use str(ObjectId), as already mentined in the comment by #Simon.
#app.route("/api/employee", methods=['POST'])
def create_employee():
json = request.get_json()
result = employee.insert_employee(json)
return { "id": str(result.inserted_id) }

This is an old thread, but as the existing answers didn't help me:
Having run
new_object = collection.insert_one(doc)
I was able to get the ObjectID with the inserted_id property:
print(f"{new_object.inserted_id}")

In python (Pymongo) there's no inbuilt method to do it so iterate over the result you fetched from db and then typecast _id to str(_id)
result = collection.find({query})
for docs in result:
docs[_id] = str(docs[_id])

first you have to assign the Object Id value to a variable
for example:
let objectId = ObjectId("543b591d91b9e510a06a42e2");
then use the toString method like this
let id = objectId.toString();

Related

Karate : Trying to convert array to string using js method toString() in karate [duplicate]

This question already has an answer here:
Change type from string to float/double for a key value of any json object in an array
(1 answer)
Closed 1 year ago.
I'm trying to convert an Array to string using a simple js function placed in the reusable feature file. I don't see any reason why the array is not getting converted to a string when I try to run the same function on the console it works without any issue.
Can anyone suggest a way to get this issue sorted?
"""
* def formatter = function(str){
var formatstring = str.toString();
return formatstring
}
"""
feature file
* def format = call read('../common/resuable.feature)
* def result = format.formatter(value)
* print result
Input = ["ID3:Jigglypuff(NORMAL)"]
Actual result = ["ID3:Jigglypuff(NORMAL)"]
Expected result = ID3:Jigglypuff(NORMAL)
[![When tried same on console][1]][1]
[1]: https://i.stack.imgur.com/tAcIz.png
Sorry, if you print an array, it will have square-brackets and all, that's just how it is.
Please unpack arrays if you want the plain string / content:
* def input = ["ID3:Jigglypuff(NORMAL)"]
* def expected = input[0]

How to convert Object(with value) into Map

I have a object that I want to print it into string [key1=value1&key2=value2...etc] without the null value key value pair and comma into &.
So first of all i think of putting it into a map but it won't work and I don know how it work either.
val wxPayOrderObj = WxPayOrder(appid = "wx0b6dcsad20b379f1", mch_id =
"1508334851", nonce_str = UUID.randomUUID().toString(),sign = null,
body = "QQTopUp", out_trade_no = "20150806125346", total_fee = req.total_fee,
spbill_create_ip = "123.12.12.123",
trade_type = "JSAPI", openid = "oUpF8uMuAJO_M2pxb1Q9zNjWeS6o")
so the output will be
appid=wx0b6dc78d20b379f1&mch_id=150788851&nonce_str=UUID.randomUUID().toString()&
body=QQTopUp&out_trade_no=20150806125346&total_fee=req.total_fee&
spbill_create_ip=123.12.12.123&trade_type=JSAPI&openid=oUpF8uMuAJO_M2pxb1Q9zNjWeS6o
anyone please help me, thanks in advances.
I don't really get your question, but you want to convert object to string (to a format that you want)?
Override the object's toString() to return "[key1=value1&key2=value2...etc]"
example
override fun toString(){
// make sure you compute the data first
val answer = "[key1=$value1&key2=$value2...etc]"
return answer
}
The $ is used in string templates (That's directly writing the name of a variable, the value will be used later to be concatenated) with other strings)

NSJSONSerialization.JSONObjectWithData changes field type

I'm getting the following JSON response from the server:
{
"userId":"123456789",
"displayName":"display name"
}
When I use NSJSONSerialization.JSONObjectWithData and then prints the result NSDictionary I see in the console the following:
userId = 123456789
displayName = "display name"
Why do JSONObjectWithData changes the userId field type from String to a number?
It doesn't. The JSON deserialisation respects the data type and will maintain it. You can't tell the data type from a simple description log, you need to actually interrogate the class. The description log will quote some things if it makes more sense for the human reader, like spaces in the description, but it also omits quotes in some cases.
It doesn't.
Don't infer a variable type from its log representation, just test. Fire a Playground with this, for example:
let str = "{\"userId\":\"123456789\",\"displayName\":\"display name\"}"
if let data = str.dataUsingEncoding(NSUTF8StringEncoding),
jsonResult = try? NSJSONSerialization.JSONObjectWithData(data, options: []),
jsonObject = jsonResult as? [String:String],
id = jsonObject["userId"] {
print("User ID is " + id)
}

Convert IList<Interface> to List<Class>

List<CurrentElectionService> result = new List<CurrentElectionService>();
result = oElectionsManager.GetCurrentElectionsByEId(
employeeId.StringToGuid(), planYear) as List<CurrentElectionService>;
Public class CurrentElectionService : ICurentElection
{
// Implement Interface fields here
}
The method GetCurrentElectionsByEId returns me IList<ICurentElection> and I want to cast the interface into class CurrentElectionService, but it returns null. Please help.
Why not use LINQ to perform your cast
List<CurrentElectionService> result = oElectionsManager.GetCurrentElectionsByEId(
employeeId.StringToGuid(), planYear).Cast<CurrentElectionService>().ToList();
I hope this helps.
You need to find out of which type the actual return value is. The as keywort always returns null if your actual object is not of the type you want to cast it to.
With the definition you gave you could also try this:
List<ICurentElection> result;
result = oElectionsManager.GetCurrentElectionsByEId(
employeeId.StringToGuid(), planYear) as List<ICurentElection>;

Return .str of ObjectID using pymongo

How would I return just the string component of an BSON ObjectId using pymongo. I'm able to encode a string into an Object id by importing ObjectId from bson.objectid; but am unable to do the reverse.
When I try:
for post in db.votes.find({'user_id':userQuery['_id']}):
posts += post['_id'].str
I get an ObjectId has no attribute str error.
Thanks!
The standard way in python to get object's string representation is using the str builtin function:
id = bson.objectid.ObjectId()
str(id)
=> '5190666674d3cc747cc12e61'
try this:
for post in db.votes.find({'user_id':userQuery['_id']}):
posts += str(post['_id'])
BTW, you can use MongoKit to deal with the special bson data structure.
from bson.objectid import ObjectId
class CustomObjectId(CustomType):
mongo_type = ObjectId # optional, just for more validation
python_type = str
init_type = None # optional, fill the first empty value
def to_bson(self, value):
"""convert type to a mongodb type"""
return ObjectId(value)
def to_python(self, value):
"""convert type to a python type"""
return str(value)
def validate(self, value, path):
"""OPTIONAL : useful to add a validation layer"""
if value is not None:
pass # ... do something here
This custom ObjectId can turn the bson ObjectId to python str.
Visit http://mongokit.readthedocs.org/mapper.html#the-structure for more information.