如何将 objectid 转换为 string

我想从 ObjectId 对象获取字符串字符。 我想得到 "543b591d91b9e510a06a42e2"

我看到医生了,上面写着 ObjectId.toString()ObjectId.valueOf()

所以我做了这个代码: from bson.objectid import ObjectId

但当我使用 ObjectId.valueOf()时,它显示:

“ ObjectId”对象没有属性“ valueOf”。

我怎么才能拿到? 谢谢。

96433 次浏览

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.

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

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

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();