Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 854
Ranjith.M Nair Avatar asked Oct 18 '17 06:10

Ranjith.M Nair


1 Answers

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.

like image 184
Jundiaius Avatar answered Sep 20 '22 09:09

Jundiaius