Thursday, June 4, 2015

Deleting an entry in Mongodb by _id in pymongo

I had to look around for a while to figure out how to delete an entry in mongodb by _id in pymongo.
Obviously its the remove function but how to pass the values was my problem. In my current app, I have a view returning list of "_id" values to be deleted. I plan to put them in a loop and get them deleted on by one(Haven't thought of a bulk query). Problem I faced was that barely passing the value did not do the trick. I could not get any objectid() function from pymongo either. The following method worked for me, I am yet to look into the pros and cons and everything else of that.

I imported the following stuff.
---
from bson import ObjectId
---

Now I ran my snippet as below.
---
for ids in posts_to_be_deleted:
    db.posts.remove({'_id':ObjectId(ids)})
---

Voila! It worked and I could sleep happily after a lot of frustration.

That's all. Feel free to point out any mistakes or alternative methods. Am just learning :)


No comments:

Post a Comment