pymongo : delete records elegantly

Question:

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?

Asked By: icn

||

Answers:

You can use the following:

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

For now collection.remove(filter) is deprecated, use collection.delete_many(filter).

Example: collection.delete_many({"author": ObjectId("...")})

Answered By: Geekmoss
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.