I'm trying to collection.remove({})
N documents using PyMongo.
On mongodb this is done like this, what's the PyMongo equivalent?
Thanks
答案 0 :(得分:2)
要删除集合中的N个文档,您可以执行
对该集合进行bulk_write
次DeleteOne
次操作。 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
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)