python连接mongodb.md

# !/usr/bin/python
# -*- coding: utf-8 -*-
from pymongo import MongoClient

class MongodbLink(object):
    """mongodb数据库操作类"""
    def __init__(self, config, collection):
        self.host = config['host']
        self.port = config['port']
        self.db = config['db']
        self.collection_name = collection
        self.user = config.get('user', '')
        self.password = config.get('password', '')
        self.conn = MongoClient(host=self.host, port=self.port)

        if self.user and self.password:
            db_auth = self.conn[self.db]
            db_auth.authenticate(self.user, self.password)
            self.collection = self.conn[self.db][self.collection_name]
        else:
            self.collection = self.conn[self.db][self.collection_name]

    def exe_insert(self, document):
        """插入数据"""
        try:
            result = self.collection.insert_one(document)
            return {'state': True, 'data': result}
        except:
            return {'state': False, 'data': None}


    def exe_remove(self, document):
        """删除数据"""
        try:
            result = self.collection.remove(document)
            return {'state': True, 'data': result}
        except:
            return {'state': False, 'data': None}

    def exe_update(self, document):
        """更新数据"""
        try:
            data = self.collection.update({"_id": document["_id"]}, document)
            result = self.collection.find_one({"_id": data["_id"]})
            return {'state': True, 'data': result}
        except:
            return {'state': False, 'data': {}}

    def exe_search_one(self, document):
        """查找一条数据"""
        try:
            result = self.collection.find_one(document)
            return {'state': True, 'data': result}
        except:
            return {'state': False, 'data': {}}

    def exe_search(self, document):
        """查找数据"""
        try:
            result = list(self.collection.find(document))
            return {'state': True, 'data': result}
        except:
            return {'state': False, 'data': []}

    def exe_count(self, document):
        """查询总数"""
        try:
            result = self.collection.find(document).count()
            return {'state': True, 'data': result}
        except:
            return {'state': False, 'data': 0}

    def exe_search_page(self, document, limit, offset):
        """翻页"""
        try:
            result = list(self.collection.find(document).limit(limit).skip(offset))
            return {'state': True, 'data': result}
        except:
            return {'state': False, 'data': []}


if __name__ == '__main__':
    opts = {
        "host": "172.16.163.8",
        "port": 27017,
        "db": "logs"
    }
    client = MongodbLink(opts, 'job_logs')
    result = client.exe_search({})
    print(result)

你可能感兴趣的:(python连接mongodb.md)