Python 操作 MongoDB 数据库的方法(非 ODM)
MongoDB 是一个基于分布式文件存储的 NoSQL 数据库,是当前非常流行的文档型数据库之一。Python 作为一门优秀的程序设计语言,拥有很好的语法和语言特性,广泛应用于各个领域,自然也可以用 Python 去操作 MongoDB 数据库。
安装 Python MongoDB 驱动
在使用 Python 进行 MongoDB 操作前,我们需要安装 MongoDB 驱动。Python 支持 MongoDB 驱动有很多种,其中最常用的是 pymongo
。安装方法如下:
pip install pymongo
或者通过 conda 安装:
conda install -c anaconda pymongo
连接 MongoDB 数据库
在 Python 中连接 MongoDB 数据库很容易,只需要使用 pymongo
模块中的 MongoClient
类即可。示例代码如下:
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client['my_db']
collection = db['my_collection']
上述代码中,MongoClient
接受两个参数:地址和端口号。我们可以使用 localhost
和 MongoDB 默认端口号 27017
来创建一个默认的连接。
插入数据
插入数据操作是 MongoDB 最常见的操作之一。在 Python 中,使用 insert_one
方法可插入单条数据,使用 insert_many
方法可插入多条数据。下面是插入单条数据和多条数据的示例代码:
# 插入单条数据
user = {'name': 'Tom', 'age': 26, 'gender': 'male'}
collection.insert_one(user)
# 插入多条数据
users = [
{'name': 'Mike', 'age': 22, 'gender': 'male'},
{'name': 'Lisa', 'age': 24, 'gender': 'female'},
{'name': 'John', 'age': 28, 'gender': 'male'}
]
collection.insert_many(users)
查询数据
查询数据是 MongoDB 操作中常用的操作之一。在 Python 中,我们可以使用 find()
方法查询数据。下面是一个简单的查询例子:
# 查询所有数据
for user in collection.find():
print(user)
# 查询指定条件的数据
for user in collection.find({'age': {'$gt': 25}}):
print(user)
上述代码使用了查询条件 {'age': {'$gt': 25}}
,表示查询年龄大于 25 岁的数据。
更新数据
更新数据也是 MongoDB 操作中常用的操作之一。在 Python 中,我们使用 update_one()
或 update_many()
方法来更新数据。下面是一个简单的更新例子:
# 更新一条数据
collection.update_one({'name': 'Tom'}, {'$set': {'age': 27}})
# 更新多条数据
collection.update_many({'gender': 'male'}, {'$set': {'age': 30}})
上述代码使用 $set
关键字来设置更新的值。表示更新 age
字段的值为 27
或 30
。
删除数据
删除数据也是 MongoDB 操作中常用的操作之一。在 Python 中,我们使用 delete_one()
或 delete_many()
方法来删除数据。下面是一个简单的删除例子:
# 删除一条数据
collection.delete_one({'name': 'Tom'})
# 删除多条数据
collection.delete_many({'gender': 'male'})
上述代码中,删除操作使用了删除条件 {'name': 'Tom'}
或 {'gender': 'male'}
,表示删除满足条件的数据。
示例说明
下面是一个完整的 Python 操作 MongoDB 数据库的示例:
from pymongo import MongoClient
# 连接 MongoDB 数据库
client = MongoClient('localhost', 27017)
db = client['my_db']
collection = db['my_collection']
# 插入数据
user = {'name': 'Tom', 'age': 26, 'gender': 'male'}
collection.insert_one(user)
users = [
{'name': 'Mike', 'age': 22, 'gender': 'male'},
{'name': 'Lisa', 'age': 24, 'gender': 'female'},
{'name': 'John', 'age': 28, 'gender': 'male'}
]
collection.insert_many(users)
# 查询数据
for user in collection.find():
print(user)
for user in collection.find({'age': {'$gt': 25}}):
print(user)
# 更新数据
collection.update_one({'name': 'Tom'}, {'$set': {'age': 27}})
collection.update_many({'gender': 'male'}, {'$set': {'age': 30}})
# 删除数据
collection.delete_one({'name': 'Tom'})
collection.delete_many({'gender': 'male'})
该程序首先连接 MongoDB 数据库,然后插入了两条数据:一条单条数据和一条多条数据。接着查询数据,更新数据和删除数据。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Python 操作 MongoDB数据库的方法(非 ODM) - Python技术站