How can I remove N documents in PyMongo?

时间:2018-03-23 00:43:36

标签: mongodb pymongo

I'm trying to collection.remove({}) N documents using PyMongo. On mongodb this is done like this, what's the PyMongo equivalent?

Thanks

1 个答案:

答案 0 :(得分:2)

要删除集合中的N个文档,您可以执行

  1. 对该集合进行bulk_writeDeleteOne次操作。 e.g。

    In [1]: from pymongo import MongoClient
            from pymongo.operations import DeleteOne
    
    
            client = MongoClient()
            db = client.test
            N = 2 
    
            result = db.test.bulk_write([DeleteOne({})] * N)
    
    In [2]: print(result.deleted_count)
    2
    
  2. delete_many使用之前find的所有ID的过滤器。 e.g。

    def delete_n(collection, n):
        ndoc = collection.find({}, ('_id',), limit=n)
        selector = {'_id': {'$in': [doc['_id'] for doc in ndoc]}}
        return collection.delete_many(selector)
    
    result = delete_n(db.test, 2)
    print(result.deleted_count)