Ranjith.M Nair
Ranjith.M Nair

Reputation: 85

Python mongoengine - retrieve _id after saving

I need a help in storing and retrieving to mongodb from python using mongoengine. I am relatievely new to mongoengine and i am trying to insert a document using something like below:

Sample code i used for saving:

session = Session()
session =  session.from_json(sessionjson)
session.save()

It is saving well and good, but is it possible to retrieve _id from the saved document? The above save is returning QuerySetManager object but it is not identifying a field called _id. Please advice on this

Upvotes: 6

Views: 3404

Answers (1)

Jundiaius
Jundiaius

Reputation: 7610

After saving, you only need to check the field "id" of your document (that's is the mongoengine attribute that represents the internal mongodb "_id").

Try:

session.save()
document_id = session.id

Before session.save(), if your document was not already in your database, the field id will be None.

Upvotes: 6

Related Questions