pymongo : delete records elegantly

icn picture icn · Dec 19, 2012 · Viewed 43.7k times · Source

Here is my code to delete a bunch of records using pymongo

ids = []
with MongoClient(MONGODB_HOST) as connection:
    db = connection[MONGODB_NAME]
    collection = db[MONGODN_COLLECTION]
    for obj in collection.find({"date": {"$gt": "2012-12-15"}}):
        ids.append(obj["_id"])
    for id in ids:
        print id
        collection.remove({"_id":ObjectId(id)})

IS there a better way to delete these records? like delete a whole set of records directly

collection.find({"date": {"$gt": "2012-12-15"}}).delete() or remove()

or delete from obj like

 obj.delete() or obj.remove()

or somehting similar?

Answer

Jorge Puente-Sarrín picture Jorge Puente-Sarrín · Dec 19, 2012

You can use the following:

collection.remove({"date": {"$gt": "2012-12-15"}})