How do i get the recent inserted document in MongoDB with all it's fields?

Viewed 780

I'm working on this REST application in python Fask and a driver called pymongo. But if someone knows mongodb well he/she maybe able to answer my question.

Suppose Im inserting a new document in a collection say students. I want to get the whole inserted document as soon as the document is saved in the collection. Here is what i've tried so far.

res = db.students.insert_one({
                "name": args["name"],
                "surname": args["surname"],
                "student_number": args["student_number"],
                "course": args["course"],
                "mark": args["mark"]
})

If i call:

print(res.inserted_id) ## i get the id

How can i get something like:

{
   "name": "student1",
   "surname": "surname1",
   "mark": 78,
   "course": "ML",
   "student_number": 2
}

from the res object. Because if i print res i am getting <pymongo.results.InsertOneResult object at 0x00000203F96DCA80>

2 Answers

Put the data to be inserted into a dictionary variable; on insert, the variable will have the _id added by pymongo.

from pymongo import MongoClient

db = MongoClient()['mydatabase']

doc = {
    "name": "name"
}

db.students.insert_one(doc)

print(doc)

prints:

{'name': 'name', '_id': ObjectId('60ce419c205a661d9f80ba23')}

Unfortunately, the commenters are correct. The PyMongo pattern doesn't specifically allow for what you are asking. You are expected to just use the inserted_id from the result and if you needed to get the full object from the collection later do a regular query operation afterwards

Related