Python pymongo : 优雅地删除记录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13960959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:01:50  来源:igfitidea点击:

pymongo : delete records elegantly

pythonmongodbpymongo

提问by icn

Here is my code to delete a bunch of records using 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)})

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 中删除

 obj.delete() or obj.remove()

or somehting similar?

或类似的东西?

采纳答案by Jorge Puente-Sarrín

You can use the following:

您可以使用以下内容:

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

回答by Geekmoss

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

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

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

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