如何使用pymongo删除一个集合?

Mor*_*ton 11 python scrapy pymongo

我使用MongoDB scarpy来抓取数据并将其保存到云托管中mLab.

我的收藏名称是recently,数据的数量是5. 在此输入图像描述

我想再次抓取数据并更新我的集合recently,所以我尝试删除集合然后插入.

这是我的代码pipelines.py:

from pymongo import MongoClient
from scrapy.conf import settings

class MongoDBPipeline(object):

    def __init__(self):
        connection = MongoClient(
            settings['MONGODB_SERVER'],
            settings['MONGODB_PORT'])
        db = connection[settings['MONGODB_DB']]
        # here is my collection name recently setting
        self.collection = db[settings['MONGODB_COLLECTION']]

    def process_item(self, item, spider):
        # try to drop my collection recently
        self.collection.drop()
        self.collection.insert(dict(item))
        return item
Run Code Online (Sandbox Code Playgroud)

但是当我运行我的蜘蛛时,我看到我的收集recently计数是10(它应该是5我想要的) 在此输入图像描述

我正在寻找一些如何删除集合的代码.它只是说db.[集合名称] .drop()

但是,当我尝试self.collection.drop()之前,它在我的情况下无效self.collection.insert(dict(item))

任何人都可以给我一些建议我的代码有什么问题?

那将是值得赞赏的.提前致谢.

Arp*_*nki 19

你需要使用drop.假设foo是一个集合

db.foo.drop()
Run Code Online (Sandbox Code Playgroud)

或者你可以使用 drop_collection

db.drop_collection(collection_name)
Run Code Online (Sandbox Code Playgroud)