【发布时间】:2018-03-23 16:40:38
【问题描述】:
我正在尝试使用 PyMongo collection.remove({}) N 个文档。
在 mongodb 上,这类似于 this,PyMongo 等价物是什么?
谢谢
【问题讨论】:
我正在尝试使用 PyMongo collection.remove({}) N 个文档。
在 mongodb 上,这类似于 this,PyMongo 等价物是什么?
谢谢
【问题讨论】:
为了删除集合中的N个文档,你可以这样做
bulk_write 的 DeleteOne 对集合的操作。 例如
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 的过滤器。 例如
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)
【讨论】: