ToB企服应用市场:ToB评测及商务社交产业平台

标题: 使用Python操作MongoDB数据库 [打印本页]

作者: 宁睿    时间: 2024-11-27 18:59
标题: 使用Python操作MongoDB数据库
目次

前言
MongoDB简介
基本概念
文档(Document):
集合(Collection):
数据库(Database):
BSON(Binary JSON):
特点
1. 高性能:
2. 可扩展性:
3. 高可用性:
4. 机动性:
5. 易于使用:
应用场景
对比关系型数据库
数据模子
性能和扩展性
功能和特性
安全性
实用场景
MongoDB安装和配置
MongoDB的安装
MongoDB的配置
启动服务
权限认证
安装MongoDB体系服务
MongoDB可视化工具
使用文档
Python操作MongoDB
安装 pymongo
连接到 MongoDB
用户认证
插入数据
查询数据
更新数据
删除数据
使用文档
完善MongoDB工具类
结语


前言

 近期看到一篇关于DB-Engines数据库排名的文章,发现MongoDB高居总排名的第五名,而且黑白关系型数据的的第一名,因此对MongoDB好很好奇,抱着学习的态度去研究一下这个超棒的技能。MongoDB 是一个基于分布式文件存储的数据库,旨在为WEB应用提供可扩展的高性能数据存储解决方案。它属于非关系型数据库(NoSQL),以其机动的文档模子、强大的查询功能和高可用性而受到广泛欢迎。Python 作为一门强大的编程语言,通过 pymongo 这个库可以非常便捷地与 MongoDB 数据库进行交互。本文将偏重介绍MongoDB的基本概念、并将其与关系型数据库进行对比、MongoDB数据库的安装和配置、使用 Python 和 pymongo 来连接 MongoDB 数据库,进行基本的增删改查(CRUD)操作,并在最后封装生成Python操作MongoDB的工具类。
MongoDB简介

MongoDB是一个开源、高性能、无模式的文档型数据库,它以其机动的文档模子和高扩展性著称,是NoSQL数据库产物中的一种。以下是MongoDB的基本概念及特点:
基本概念

文档(Document)


集合(Collection)


数据库(Database)


BSON(Binary JSON)


特点

1. 高性能


2. 可扩展性


3. 高可用性


4. 机动性


5. 易于使用


应用场景

MongoDB实用于处理大规模的数据存储和查询需求,特殊是在以了局景中表现优异:

比方,MongoDB在交际媒体、电子商务、物联网等领域有广泛的应用。
总之,MongoDB是一个功能强大、机动易用的文档型数据库,它以其高性能、可扩展性和机动性而受到广泛欢迎。随着大数据和云计算技能的不断发展,MongoDB的应用远景将更加广阔。
对比关系型数据库

在工作中主要使用MySQL数据库,以是这里主要对比MongoDB和MySQL数据库的异同。MongoDB是NoSQL数据库产物中的一种,MySQL是关系型数据库的一种,它们各自在数据模子、性能、功能、安全性等方面存在显著差异。以下是对MongoDB和MySQL的详细对比:
数据模子


性能和扩展性


功能和特性


安全性


实用场景


MongoDB安装和配置

MongoDB的安装

从https://www.mongodb.com/try/download/community所在选择合适的版本下载MongoDB msi安装包。双击安装包直接安装,留意选择合适的安装目次,本人安装位置为:D:\mongoDB\目次下。
MongoDB的配置

启动服务

首先要在MongoDB的data文件夹里新建一个db文件夹和一个log文件夹,然后在log文件夹下新建一个mongo.log文件,然后将D:\mongoDB\bin添加到情况变量path中,接着在cmd窗口中运行如下下令就可以启动mongoDB服务:
  1. mongod --dbpath D:\mongoDB\data\db
复制代码
此时打开cmd窗口运行一下mongo下令即可连接上MongoDB服务。
权限认证

连接上MongoDB服务,实行如下下令,添加用户名和密码:
  1. use admin
  2. db.createUser({
  3.     user: 'yourUsername',
  4.     pwd: 'yourPassword',
  5.     roles: [ { role: 'userAdminAnyDatabase', db: 'admin' } ]
  6. })
复制代码
接着打开D:\mongoDB\bin\mongod.cfg文件,打开如下配置:
  1. security:
  2.   authorization: enabled
复制代码
这个配置是针对MongoDB的,它启用了MongoDB的权限认证。
接着启动MongoDB服务,使用如下下令:
  1. mongod --config D:\mongoDB\bin\mongod.cfg --dbpath=D:\mongoDB\data --logpath=D:\mongoDB\data\mongodb.log
复制代码
MongoDB服务启动乐成,接着可以使用如下下令连接服务:
  1. mongo -u user -p password123 --authenticationDatabase admin
复制代码
安装MongoDB体系服务

但是如果每次都要这么启动服务的话也太麻烦了吧,这里你可以选择设置成开机自启动,也可以选择用下令net start mongodb来手动启动,这里我选择使用后者,具体方法如下:
  1. mongod --config D:\mongoDB\bin\mongod.cfg --dbpath=D:\mongoDB\data --logpath=D:\mongoDB\data\mongodb.log -install -serviceName "MongoDB"
复制代码
如果没有报错的话就说明乐成添加到服务里了,可以使用win+R然后输入services.msc下令进行查看:

MongoDB可视化工具

本人习惯使用Navicat for MongoDB作为可视化工具,具体用法不再赘述,请自行搜刮,这里直接上图:


Navicat下载链接
使用文档

详细的MongoDB操作请参考官方文档
Python操作MongoDB

安装 pymongo

首先,确保你的情况中已经安装了 MongoDB 数据库,并且它正在运行。然后,你需要安装 pymongo 库。在你的 Python 情况中,可以使用 pip 下令来安装:
  1. pip install pymongo
复制代码
连接到 MongoDB

使用 pymongo 连接到 MongoDB 数据库非常简单。以下是一个基本的连接示例:
  1. from pymongo import MongoClient
  2. # 连接到本地 MongoDB 服务
  3. # 默认端口是 27017
  4. client = MongoClient('localhost', 27017)
  5. # 选择或创建数据库
  6. db = client['mydatabase'] # 如果数据库不存在,将会自动创建
  7. # 选择或创建集合
  8. collection = db['mycollection'] # 集合类似于关系数据库中的表
复制代码
用户认证

  1. from pymongo import MongoClient
  2. # 连接到本地 MongoDB 服务
  3. # 默认端口是 27017
  4. client = MongoClient(host='127.0.0.1', port=27017,username="admin",password="*****")
  5. # 选择或创建数据库
  6. db = client['mydatabase'] # 如果数据库不存在,将会自动创建
  7. # 选择或创建集合
  8. collection = db['mycollection'] # 集合类似于关系数据库中的表
复制代码
插入数据

在 MongoDB 中,文档是存储数据的基本单元,相当于关系数据库中的行。你可以使用 insert_one() 方法插入单个文档,大概使用 insert_many() 方法插入多个文档。
  1. # 插入单个文档
  2. post = {"author": "John", "text": "My first blog post!", "tags": ["mongodb", "python", "pymongo"]}
  3. post_id = collection.insert_one(post).inserted_id
  4. print("Inserted post with ID:", post_id)
  5. # 插入多个文档
  6. posts = [
  7. {"author": "Alice", "text": "Another post", "tags": ["web", "databases"]},
  8. {"author": "Bob", "text": "Yet another post", "tags": ["developers", "blogging"]},
  9. ]
  10. collection.insert_many(posts)
复制代码
查询数据

MongoDB 提供了丰富的查询接口。以下是一些基本示例:
  1. # 查询所有文档
  2. for post in collection.find():
  3.     print(post)
  4. # 使用查询条件
  5. for post in collection.find({"author": "John"}):
  6.     print(post)
  7. # 投影(只返回指定字段)
  8. for post in collection.find({}, {"_id": 0, "text": 1}):
  9.     print(post)
复制代码
更新数据

使用 update_one() 或 update_many() 方法可以更新文档。
  1. # 更新单个文档
  2. collection.update_one({"author": "John"}, {"$set": {"text": "Updated text"}})
  3. # 更新多个文档
  4. collection.update_many({"tags": "mongodb"},{"$set": {"text": "MongoDB post updated"}})
复制代码
删除数据

使用 delete_one() 或 delete_many() 方法可以删除文档。
  1. collection.delete_one({"author": "Alice"})
  2. # 删除多个文档
  3. collection.delete_many({"tags": "blogging"})
复制代码
使用文档

详细的pymongo操作请参考官方文档
完善MongoDB工具类

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. @Time    : 2024/7/19 下午3:19
  5. @Author  : Bill Fang
  6. @File    : MongoDBUtil.py
  7. @Desc    :
  8. """
  9. import pymongo
  10. class MongoDBUtil:
  11.     """
  12.     MongoDB工具类
  13.     """
  14.     def __init__(self, ip="127.0.0.1", db_name=None, port=27017):
  15.         """构造函数"""
  16.         self.client = pymongo.MongoClient(host=ip, port=port,username="admin",password="****")
  17.         self.database = self.client[db_name]
  18.         print(self.database)
  19.     def create_database(self, db_name):
  20.         """创建数据库"""
  21.         return self.client.get_database(db_name)
  22.     def drop_database(self, db_name):
  23.         """删除数据库"""
  24.         return self.client.drop_database(db_name)
  25.     def select_database(self, db_name):
  26.         """使用数据库"""
  27.         self.database = self.client[db_name]
  28.         return self.database
  29.     def get_database(self, db_name):
  30.         """使用数据库"""
  31.         # return self.client[db_name]
  32.         return self.client.get_database(db_name)
  33.     def list_database_names(self):
  34.         """获取所有数据库列表"""
  35.         return self.client.list_database_names()
  36.     def create_collection(self, collect_name):
  37.         """创建集合"""
  38.         collect = self.database.get_collection(collect_name)
  39.         if(collect is not None):
  40.             print("collection %s already exists" % collect_name)
  41.             return collect
  42.         return self.database.create_collection(collect_name)
  43.     def drop_collection(self, collect_name):
  44.         """获取所有集合名称"""
  45.         return self.database.drop_collection(collect_name)
  46.     def get_collection(self, collect_name):
  47.         """获取集合"""
  48.         return self.database.get_collection(collect_name)
  49.     def list_collection_names(self):
  50.         """获取所有集合名称"""
  51.         return self.database.list_collection_names()
  52.     def insert(self, collect_name, documents):
  53.         """插入单条或多条数据"""
  54.         return self.database.get_collection(collect_name).insert(documents)
  55.     def insert_one(self, collect_name, document):
  56.         """插入一条数据"""
  57.         return self.database.get_collection(collect_name).insert_one(document)
  58.     def insert_many(self, collect_name, documents):
  59.         """插入多条数据"""
  60.         return self.database.get_collection(collect_name).insert_many(documents)
  61.     def delete_one(self, collect_name, filter, collation=None, hint=None, session=None):
  62.         """删除一条记录"""
  63.         return self.database.get_collection(collect_name).delete_one(filter, collation, hint, session)
  64.     def delete_many(self, collect_name, filter, collation=None, hint=None, session=None):
  65.         """删除所有记录"""
  66.         return self.database.get_collection(collect_name).delete_many(filter, collation, hint, session)
  67.     def find_one_and_delete(self, collect_name, filter, projection=None, sort=None, hint=None, session=None, **kwargs):
  68.         """查询并删除一条记录"""
  69.         return self.database.get_collection(collect_name).find_one_and_delete(filter, projection, sort, hint, session, **kwargs)
  70.     def count_documents(self, collect_name, filter, session=None, **kwargs):
  71.         """查询文档数目"""
  72.         return self.database.get_collection(collect_name).count_documents(filter, session, **kwargs)
  73.     def find_one(self, collect_name, filter=None, *args, **kwargs):
  74.         """查询一条记录"""
  75.         return self.database.get_collection(collect_name).find_one(filter, *args, **kwargs)
  76.     def find(self, collect_name, *args, **kwargs):
  77.         """查询所有记录"""
  78.         return self.database.get_collection(collect_name).find(*args, **kwargs)
  79.     def update(self, collect_name, spec, document, upsert=False, manipulate=False,
  80.                multi=False, check_keys=True, **kwargs):
  81.         """更新所有记录"""
  82.         return self.database.get_collection(collect_name).update(spec, document,
  83.                                 upsert, manipulate, multi, check_keys, **kwargs)
  84.     def update_one(self, collect_name, filter, update, upsert=False, bypass_document_validation=False,
  85.                                 collation=None, array_filters=None, hint=None, session=None):
  86.         """更新一条记录"""
  87.         return self.database.get_collection(collect_name).update_one(filter, update,
  88.                                 upsert, bypass_document_validation, collation, array_filters, hint, session)
  89.     def update_many(self, collect_name, filter, update, upsert=False, array_filters=None,
  90.                                 bypass_document_validation=False, collation=None, hint=None, session=None):
  91.         """更新所有记录"""
  92.         return self.database.get_collection(collect_name).update_many(filter, update,
  93.                                 upsert, array_filters, bypass_document_validation, collation, hint, session)
  94.     def find_one_and_update(self, collect_name, filter, update, projection=None, sort=None, upsert=False,
  95.                            return_document=False, array_filters=None, hint=None, session=None, **kwargs):
  96.         """查询并更新一条记录"""
  97.         return self.database.get_collection(collect_name).find_one_and_update(filter, update, projection,
  98.                                 sort, upsert, return_document, array_filters, hint, session, **kwargs)
复制代码
结语

以上就是使用Python操作MongoDB数据库的基本介绍。通过PyMongo库,我们可以轻松地实现数据库的增删改查等操作。盼望这篇博客对各人有所资助,也等待各人在学习和使用MongoDB的过程中,能够创造出更多风趣和实用的应用!




免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4