简体   繁体   English

从Pymongo中的收藏中删除文件?

[英]Deleting documents from collection in Pymongo?

I have the following: 我有以下几点:

from pymongo import MongoClient
client = MongoClient()
db=client.localhost
collection=db['accounts']
db.collection.remove({})

cursor = collection.find({})
for document in cursor:
    print(document)

This second part is to just print all the documents in the collection. 第二部分是仅打印集合中的所有文档。 However, the collection isn't clearing every time I rerun the program. 但是,每次我重新运行程序时,集合不会清除。 Does anyone know why? 有人知道为什么吗?

Instead of doing this 而不是这样做

db.collection.remove({})

do this 做这个

db.accounts.remove({})

Also you won't need this line collection=db['accounts'] 另外,您将不需要此行collection=db['accounts']

If you want dynamic collection name, you can do the following: 如果要使用动态集合名称,可以执行以下操作:

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

Instead of 代替

db.collection.remove({})

you can try this 你可以试试这个

collection.delete_many({})

Hope that solves your problem. 希望能解决您的问题。

做这个

db.accounts.drop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM