0

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

Thanks

Forepick
  • 919
  • 2
  • 11
  • 31

1 Answers1

2

In order to remove N documents in a collection, you can do

  1. A bulk_write of DeleteOne operations on the collection. 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. A delete_many using a filter of all ids from a previous find. 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)
    
Oluwafemi Sule
  • 36,144
  • 1
  • 56
  • 81