Python操作MongoDB数据库

Python操作MongoDB数据库

1.MongoDB介绍

MongoDB是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。它支持的数据结构非常松散,是类似jsonbson格式,因此可以存储比较复杂的数据类型。Mongo最大的特点是它支持的查询语言非常强大,其语法有点类似于面向对象的查询语言,几乎可以实现类似关系数据库单表查询的绝大部分功能,而且还支持对数据建立索引。

2.安装pymongo库
pip install pymongo
3.python操作MongoDB

(1)创建连接connection

(2)指定数据库

(3)指定集合

(4)执行插入、更改、查询、删除语句获取数据处理数据

import pymongo

class MongoConfig:
    HOST = "127.0.0.1"
    PORT = 27017
    USER = "admin"
    PWD = "admin"
    DB = "person"  # 指定数据库


class MongoConnection:
    def __init__(self,ip=MongoConfig.HOST,port=MongoConfig.PORT,
                 user=MongoConfig.USER,pwd=MongoConfig.PWD,
                                           db=MongoConfig.DB):
        # 1.创建连接 mongodb://用户名:密码@ip:端口
        client = pymongo.MongoClient(
            f"mongodb://{user}:{pwd}@{ip}:{port}"
        )

        # 2.指定数据库
        self.db = client[db]

    def insert(self,collection,query,many=False):
        """
        插入方法
        :param collection: 集合
        :param query: 数据
        :param many: 控制是否匹配多个
        :return:
        """
        # 指定集合

        data_collection=self.db[collection]
        if many:
             data_collection.insert_many(query)
        else:
             data_collection.insert_one(query)


    def find(self,collection,query,many=True):
        data_collection = self.db[collection]
        if many:
            result=[]
            results=data_collection.find(query)
            for data in results:
                result.append(data)
            return result
        else:
            result=data_collection.find_one(query)
            return result


    def update(self,collection,query,new_value,many=False):
        data_collection = self.db[collection]
        if many:
            data_collection.update_many(query,{"$set":new_value})
        else:
            data_collection.update_one(query, {"$set": new_value})


    def delete(self,collection,query,many=False):
        data_collection = self.db[collection]
        if many:
            data_collection.delete_many(query)
        else:
            data_collection.delete_one(query)
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python操作MongoDB数据库需要用到pymongo库,安装方法如下: ``` pip install pymongo ``` 连接数据库: ```python from pymongo import MongoClient # 连接MongoDB数据库 client = MongoClient('mongodb://localhost:27017/') ``` 通过client对象获取数据库和集合: ```python # 获取数据库对象 db = client.testdb # 获取集合对象(类似于关系数据库中的表) collection = db.test_collection ``` 插入数据: ```python # 插入一条数据 post = {"author": "Mike", "text": "My first blog post!", "tags": ["mongodb", "python", "pymongo"]} collection.insert_one(post) # 插入多条数据 new_posts = [{"author": "Mike", "text": "Another post!", "tags": ["bulk", "insert"], "date": datetime.datetime(2009, 11, 12, 11, 14)}, {"author": "Eliot", "title": "MongoDB is fun", "text": "and pretty easy too!", "date": datetime.datetime(2009, 11, 10, 10, 45)}] collection.insert_many(new_posts) ``` 查询数据: ```python # 查询所有数据 for post in collection.find(): print(post) # 条件查询 query = {"author": "Mike"} for post in collection.find(query): print(post) # 正则表达式查询 query = {"author": {"$regex": "^M.*"}} for post in collection.find(query): print(post) ``` 修改数据: ```python # 更新一条数据 result = collection.update_one( {"author": "Mike"}, {"$set": {"text": "My first blog post (update)!"}} ) print("影响的文档数量:", result.modified_count) # 更新多条数据 result = collection.update_many( {"author": "Mike"}, {"$set": {"text": "My first blog post (update)!"}} ) print("影响的文档数量:", result.modified_count) ``` 删除数据: ```python # 删除一条数据 result = collection.delete_one({"author": "Mike"}) print("影响的文档数量:", result.deleted_count) # 删除多条数据 result = collection.delete_many({"author": "Mike"}) print("影响的文档数量:", result.deleted_count) # 删除所有数据 result = collection.delete_many({}) print("影响的文档数量:", result.deleted_count) ``` 关闭连接: ```python # 关闭连接 client.close() ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值