How to Get Id of Inserted Document in Python MongoDB


In this example, we will learn how to get the id of the inserted document in Python MongoDB.

Source Code

from pymongo import MongoClient

client = MongoClient("localhost", 27017)
db = client["mydatabase"]
collection = db["us_state"]

record = {"State_name": "Alaska", "Abbreviation": "AK", "Capital": "Juneau", "Total_area": 665384}

a = collection.insert_one(record)
print(a.inserted_id)

Output:

5f22f02f7269d714fe3c2454
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Advertisement