john_zh john_zh - 2 months ago 5x
Python Question

How to delete the last item of a collection in mongodb

I made a program with python and mongodb to do some diaries. Like thisslice diary

Sometimes I want to delete the last sentence, just by typing "delete!"
But I dont know how to delete in a samrt way. I dont want to use "skip".
Is there a good way to do it?


Be it first or last item, MongoDB maintains unique _id key for each record and thus you can just pass that id field in your delete query either using deleteOne() or deleteMany(). Since only one record to delete you need to use deleteOne() like

db.collection_name.deleteOne({"_id": "1234"}) // replace 1234 with actual id