How to delete the last item of a collection in mongodb

这一生的挚爱 提交于 2021-02-18 19:32:27

问题


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

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?


回答1:


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


来源:https://stackoverflow.com/questions/39030332/how-to-delete-the-last-item-of-a-collection-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!