【pymongo】python封装pymongo操作集合增删改查文档

1、pymongo官网

https://pypi.org/project/pymongo/

https://api.mongodb.com/

 

2、github

https://github.com/mongodb/mongo-python-driver

 

3、文档

https://www.osgeo.cn/mongo-python-driver/api/pymongo/collection.html

https://pymongo.readthedocs.io/en/stable/

 

4、安装

pip install pymongo

 

5、封装

复制代码
from pymongo import MongoClient


class MongoConnectClient(object):
    def __init__(self, db, collect_name, uri='mongodb://localhost:27017/'):
        self.uri = uri
        # self.client = MongoClient(self.host, self.port)
        self.client = MongoClient(self.uri)
        self.db = self.client.get_database(db)
        self.col = self.db.get_collection(collect_name)

    def close(self):
        self.client.close()

    def find_many(self, condition=None):
        if not condition:
            condition = {}
        cursor_obj = self.col.find(condition)
        result = [data for data in cursor_obj]
        return result

    def insert_one(self, data):
        return self.col.insert_one(data).inserted_id

    def insert_many(self, data_list):
        return self.col.insert_many(data_list).inserted_ids

    def update_many(self, condition, new_values):
        if not condition:
            raise Exception("condition is None")
        return self.col.update_many(condition, new_values).raw_result

    def delete_many(self, condition):
        if not condition:
            raise Exception("condition is None")
        return self.col.delete_many(condition).raw_result


if __name__ == '__main__':
    mc = MongoConnectClient("test", "user")
    print(mc.db.list_collection_names())
复制代码

 

 

参考链接:

https://blog.51cto.com/u_13567403/3042298

 

posted @   代码诠释的世界  阅读(372)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示