从Pymongo删除收藏文档



我有以下内容:

from pymongo import MongoClient
client = MongoClient()
db=client.localhost
collection=db['accounts']
db.collection.remove({})
cursor = collection.find({})
for document in cursor:
    print(document)

第二部分是只打印集合中的所有文档。但是,每次我重新运行该程序时,该系列并不是清算。有人知道为什么吗?

只是做这个

db.accounts.drop()

而不是

db.collection.remove({})

您可以尝试此

collection.delete_many({})

希望解决您的问题。

而不是这样做

db.collection.remove({})

做这个

db.accounts.remove({})

您也不需要此行collection=db['accounts']

如果您想要动态收集名称,则可以执行以下操作:

collection_name = 'accounts'
getattr(db, collection_name).remove({})

最新更新