john_zh john_zh - 1 year ago 83
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?

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download