Python 的 pymongo
库是 MongoDB 的官方 Python 驱动程序,它允许 Python 应用程序与 MongoDB 数据库进行交互。pymongo
提供了全功能的接口,用于操作 MongoDB 数据库,包括连接和配置数据库、创建和删除集合、插入和查询文档等。
此外,它还支持高级功能,如索引管理、聚合框架和网格FS。pymongo
库使用起来非常灵活,既可以用于简单的数据存储和检索,也可以用于复杂的数据分析和处理任务。它适用于需要快速开发和大数据操作的应用程序,如实时数据分析、内容管理系统和社交网络平台。通过 pymongo
,开发者可以轻松地利用 MongoDB 的高性能和高可用性特性,构建可扩展的数据驱动应用程序。
pip3 install pymongo
不仅仅安装了pymongo,还安装了dnspython,dnspython是dns工具。它可用于查询、区域传输、动态更新、名称服务器测试和许多其他事情。
from pymongo import MongoClient
# 连接方式一
client = MongoClient(host='localhost',port=27017)
# 连接方式二
# client = MongoClient('mongodb://localhost:27017/')
MongoDB 可以创建很多 db,指定我们需要的 db 即可
# 方式一
db = client.Monitor
# 方式二
# db = client['Monitor']
db 内包含很多个集合,有点类似 mysql 这类关系型数据库中的表
# 方式一
collection = db.test
# 方式二
# collection = db['test']
mongodb原生语句命令 - 查 - db.xx.find() - 与mysql对比)
rep = collection.find({}, {'field1': 1}).sort([('_id', -1)]).limit(1)
rep = collection.insert_one(dic)
rep = collection.insert_many(lists)
rep = collection.find(dic)
rep = collection.find({'yourCollectionName':{'$regex':'^yourWords'}}) # 正则表达式
rep = collection.find_one(dic)
rep = collection.update_one(condition,{'$set':dic})
rep = collection.update_many(condition,{'$set':dic})
rep = collection.delete_one(dic)
rep = collection.delete_many(dic)
rep = collection.find({},{'field1': 1}).distinct("field2")
只返回列表:['a','b']
这里只有方法名,具体看MongoDB
rep = collection.find().sort('time_field', -1).limit(10) # 时间最前10条
# 查询字段col_name的最大值
max_value = collection.find().sort('col_name', -1).limit(1)[0]['col_name']
# 文章操作
from app import mongo_client
class collection_doc():
def __init__(self):
self.db = "test" # 数据库名
self.collection = "test" # 表名
# 查
def find(self, id):
try:
data = mongo_client[self.db][self.collection].find({"_id":id})
return data
except:
raise
# 改
def update(self, id, name, today):
try:
mongo_client[self.db][self.collection].update_one({"_id":id}, {"$set":{条件}})
except:
raise
# 增
def insertMany(self, data):
try:
mongo_client[self.db][self.collection].insert_many(data)
except:
raise
写成类的好处很多:
1、可以随时复制多一个类,换一个数据库名和表名,还有一些写法留着,修改一下参数就可以使用了。
2、以后有可能进行一些修改,快速找到库曾经在什么地方使用过,以便后续更改。
3、业务逻辑更清晰,因为业务逻辑很有可能涉及各种数据库、缓存、执行顺序、条件判断的影响。
from pymongo import MongoClient
# MongoDB分片配置服务器地址列表
config_servers = [
"configsvr1.example.com:27019",
"configsvr2.example.com:27019",
"configsvr3.example.com:27019"
]
# MongoDB分片键
shard_key = "myShardKey"
# 创建MongoClient实例连接到分片集群
client = MongoClient(config_servers, replicaSet="shard0/shard1/shard2")
# 获取数据库和集合,进行数据操作
db = client.mydb
collection = db.mycollection
# 示例:插入文档
collection.insert_one({shard_key: "value1", "data": "example data"})
确保替换
configsvr1.example.com:27019,
configsvr2.example.com:27019,
configsvr3.example.com:27019
为你的配置服务器地址,
以及shard0/shard1/shard2为你的副本集名称replicaSet。
同时,替换mydb和mycollection为你的数据库和集合名称。
https://www.osgeo.cn/mongo-python-driver/changelog.html
这是变更目录,有一些奇奇怪怪的问题在这里得到解决,例如更新版本才可以解决等等