Python操作MongoDB的封裝類(lèi)

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Buckler
# Version: 2.0
# CreateTime: 2021/11/9 10:39
# UpdateTime: 2022/3/10 11:50
# Description: MongoDB數(shù)據(jù)庫(kù)操作封裝
# UpdateNote: 新增統(tǒng)計(jì)集合總量;新增分頁(yè)查詢(xún);
import sys
import pymongo


class MongoDBHelper(object):
    def __init__(self, db='default', uri='mongodb://localhost:27017/'):
        '''初始化連接'''
        self.connect_client = pymongo.MongoClient(uri)
        self.mydb = self.connect_client[db]  # 連接指定數(shù)據(jù)庫(kù)

    def insert_collection(self, collection_name, value):  # 單個(gè)插入
        mycol = self.mydb[collection_name]
        mycol_id = mycol.insert_one(value)
        return mycol_id.inserted_id  # 返回insert_id,即插入文檔的id值

    def insert_batch_collection(self, collection_name, value_list):  # 批量插入
        mycol = self.mydb[collection_name]
        mycol_id = mycol.insert_many(value_list)
        return mycol_id.inserted_ids  # 返回insert_id集合,即插入文檔的id值

    def select_one_collection(self, collection_name, search_col=None):  # 獲取一條數(shù)據(jù)
        '''search_col:只能是dict類(lèi)型,key大于等于一個(gè)即可,也可為空
        可使用修飾符查詢(xún):{"name": {"$gt": "H"}}#讀取 name 字段中第一個(gè)字母 ASCII 值大于 "H" 的數(shù)據(jù)
        使用正則表達(dá)式查詢(xún):{"$regex": "^R"}#讀取 name 字段中第一個(gè)字母為 "R" 的數(shù)據(jù)'''
        my_col = self.mydb[collection_name]
        try:
            result = my_col.find_one(search_col)  # 這里只會(huì)返回一個(gè)對(duì)象,數(shù)據(jù)需要自己取
            return result
        except TypeError as e:
            print('查詢(xún)條件只能是dict類(lèi)型')
            return None

    def select_all_collection(self, collection_name, search_col=None, limit_num=sys.maxsize, sort_col='None_sort',
                              sort='asc'):
        '''search_col:只能是dict類(lèi)型,key大于等于一個(gè)即可,也可為空
        可使用修飾符查詢(xún):{"name": {"$gt": "H"}}#讀取 name 字段中第一個(gè)字母 ASCII 值大于 "H" 的數(shù)據(jù)
        使用正則表達(dá)式查詢(xún):{"$regex": "^R"}#讀取 name 字段中第一個(gè)字母為 "R" 的數(shù)據(jù)
        limit_num:返回指定條數(shù)記錄,該方法只接受一個(gè)數(shù)字參數(shù)(sys.maxsize:返回一個(gè)最大的整數(shù)值)'''
        my_col = self.mydb[collection_name]
        try:
            if sort_col == False or sort_col == 'None_sort':
                results = my_col.find(search_col).limit(limit_num)  # 這里只會(huì)返回一個(gè)對(duì)象,數(shù)據(jù)需要自己取
            else:
                sort_flag = 1
                if sort == 'desc':
                    sort_flag = -1
                results = my_col.find(search_col).sort(sort_col, sort_flag).limit(limit_num)  # 這里只會(huì)返回一個(gè)對(duì)象,數(shù)據(jù)需要自己取
            result_all = [i for i in results]  # 將獲取到的數(shù)據(jù)添加至list
            return result_all
        except TypeError as e:
            print('查詢(xún)條件只能是dict類(lèi)型')
            return None

    def select_page_query(self, collection_name, query_filter=None, page_size=10, page_no=1):
        '''
        pymongo 分頁(yè)查詢(xún)
        :param collection_name:
        :param query_filter:
        :param page_size:
        :param page_no:
        :return:
        '''
        my_col = self.mydb[collection_name]
        try:
            skip = page_size * (page_no - 1)
            results = my_col.find(query_filter).limit(page_size).skip(skip)
            page_result = [i for i in results]
            return page_result
        except TypeError as e:
            print('查詢(xún)出錯(cuò)')
            return None

    def select_count_all(self, collection_name):
        '''
        統(tǒng)計(jì)集合中文檔總量
        :param collection_name:
        :return:
        '''
        my_col = self.mydb[collection_name]
        try:
            result = my_col.count()
            return result
        except TypeError as e:
            print('統(tǒng)計(jì)出錯(cuò)')
            return 0

    def update_one_collecton(self, collection_name, search_col, update_col):
        '''該方法第一個(gè)參數(shù)為查詢(xún)的條件,第二個(gè)參數(shù)為要修改的字段。
            如果查找到的匹配數(shù)據(jù)多余一條,則只會(huì)修改第一條。
            修改后字段的定義格式: { "$set": { "alexa": "12345" } }'''
        my_col = self.mydb[collection_name]
        try:
            relust = my_col.update_one(search_col, update_col)
            return relust
        except TypeError as e:
            print('查詢(xún)條件與需要修改的字段只能是dict類(lèi)型')
            return None

    def update_batch_collecton(self, collection_name, search_col, update_col):
        '''批量更新數(shù)據(jù)'''
        my_col = self.mydb[collection_name]
        try:
            relust = my_col.update_many(search_col, update_col)
            return relust
        except TypeError as e:
            print('查詢(xún)條件與需要修改的字段只能是dict類(lèi)型')
            return None

    def delete_one_collection(self, collection_name, search_col):  # 刪除集合中的文檔
        my_col = self.mydb[collection_name]
        try:
            relust = my_col.delete_one(search_col)
            return relust
        except TypeError as e:
            print('查詢(xún)條件與需要修改的字段只能是dict類(lèi)型')
            return None

    def delete_batch_collection(self, collection_name, search_col):  # 刪除集合中的多個(gè)文檔
        '''刪除所有 name 字段中以 F 開(kāi)頭的文檔:{ "name": {"$regex": "^F"} }
        刪除所有文檔:{}'''
        my_col = self.mydb[collection_name]
        try:
            relust = my_col.delete_many(search_col)
            return relust
        except TypeError as e:
            print('查詢(xún)條件與需要修改的字段只能是dict類(lèi)型')
            return None

    def drop_collection(self, collection_name):
        '''刪除集合,如果刪除成功 drop() 返回 true,如果刪除失敗(集合不存在)則返回 false'''
        my_col = self.mydb[collection_name]
        result = my_col.drop()
        return result

    def get_connections(self):  # 獲取所有的connections
        return self.mydb.list_collection_names()

    def close_connect(self):
        self.connect_client.close()
        return 'mongo連接已關(guān)閉'
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容