pymongo:优雅地删除记录

icn*_*icn 22 python mongodb pymongo

这是我使用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)})
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来删除这些记录?比如直接删除一整套记录

collection.find({"date": {"$gt": "2012-12-15"}}).delete() or remove()
Run Code Online (Sandbox Code Playgroud)

或者从obj中删除

 obj.delete() or obj.remove()
Run Code Online (Sandbox Code Playgroud)

或类似的?

Jor*_*rín 62

您可以使用以下内容:

collection.remove({"date": {"$gt": "2012-12-15"}})
Run Code Online (Sandbox Code Playgroud)

  • 如果你知道id,你可以简单地`collection.remove(dupId)` (5认同)
  • Python 3, Mongo 3.6: `result = collection.delete_many({"date": {"$gt": "2012-12-15"}})` `print(f'{result.deleted_count} docs deleted')` (2认同)

Gee*_*oss 12

目前collection.remove(filter)已弃用,请使用collection.delete_many(filter).

例子: collection.delete_many({"author": ObjectId("...")})