32

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?

icn
  • 17,126
  • 39
  • 105
  • 141

2 Answers2

72

You can use the following:

collection.remove({"date": {"$gt": "2012-12-15"}})
Juan Carlos Farah
  • 3,829
  • 30
  • 42
  • 6
    if you know the id, you can simply `collection.remove(dupId)` – Cmag Feb 10 '15 at 00:07
  • Note that `collection.remove(dupId)` expects an `ObjectId('some-hex-id')` rather than just the `'some-hex-id'` string – kevlarr Nov 13 '18 at 16:35
  • 2
    Python 3, Mongo 3.6: `result = collection.delete_many({"date": {"$gt": "2012-12-15"}})` `print(f'{result.deleted_count} docs deleted')` – Ryan Loggerythm Dec 11 '18 at 02:56
13

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

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

Geekmoss
  • 637
  • 6
  • 11