1.我们可以通过_id找到一条数据,
from pprint import pprint
from pymongo import MongoClient
from bson.objectid import ObjectId
client = MongoClient('localhost', 27017)
db = client['test']
collection = db['col']
pprint(collection.find_one({"_id":ObjectId("59eb50391fe637128047b053")}))
注意,ObjectId与它的字符串表示不同:
collection.find_one({"_id":"59eb50391fe637128047b053"})
查询不到任何结果 No result
2.web应用程序中的一个常见任务是从请求URL获取一个ObjectId并找到匹配的数据。在此情况下,需要将目标从字符串转换为ObjectId:
from bson.objectid import ObjectId
# The web framework gets post_id from the URL and passes it as a string
def get(post_id):
# Convert from string to ObjectId:
document = client.db.collection.find_one({'_id': ObjectId(post_id)})