欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

pymongo 使用

程序员文章站 2022-05-28 17:06:34
...
# @Time : 2019/11/30 18:06
# @Author : GKL
# FileName : mongodb去重.py
# Software : PyCharm

import pymongo
# 去重异常捕获
from pymongo.errors import DuplicateKeyError


class MongoDb(object):

    def __init__(self):
        self.client = pymongo.MongoClient()
        self.db = self.client['proxy']
        self.collection = self.db['proxy']
        # 去重操作(通过ip去重)
        self.collection.ensure_index('ip', unique=True)

    def insert(self, data):
        try:
            self.collection.insert_one(data)
        except DuplicateKeyError as e:
            print(e)


    def delete(self, conditions):
        result = self.collection.remove(conditions)
        if result['n'] == 1:
            print(f'删除成功:{conditions}')
            return True
        elif result['n'] == 0:
            print(f'删除失败:{conditions}')
            return False

    def update(self, conditions, value):
        self.collection.update(conditions, {"$set": value})
        print(f'更新{conditions}的数据为{value}')

    def get(self, count):
        count = int(count)

        items = self.collection.find({}, limit=count).sort(
            'delay', pymongo.ASCENDING
        )
        items = [{'ip': i['ip']} for i in items]
        return items

    def get_count(self, conditions=None):
        conditions = {} if conditions is None else conditions
        return self.collection.count(conditions)

if __name__ == '__main__':
    data = {
        'name': "python",
        'age': 18
    }
    s = MongoDb()
    s.insert(data)


相关标签: database