如何使用 Python 从 ObjectID 获取 ID?

How do I get the id from an ObjectID, using Python?

我正在尝试使用 PyMongo 从 MongoDB 中的文档中获取 ID。

这是我的代码:

docQuery = db.doctors.find({"email":doc_mail})
doc_id = docQuery[0]["_id"]["$oid"]

我也试过这个:

 doc_id = docQuery[0]["_id"]

两者都不行!

虽然您的第二种方法应该有效,但 docQuery 是一个 Cursor 类型的对象。最好的方法是像这样迭代它:

for itm in db.doctors.find({"email":doc_mail}):
   print itm.get('_id')

或者如果只有一个对象,则使用find_one,如:

itm = db.doctors.find_one({"email":doc_mail})
print itm.get('_id')

在pymongo中你可以使用['']这个符号来访问特定的属性。
示例 -

cursor = collection.find({})
for document in cursor:
        print document['_id']