Python操作MongoDB实战:从安装到增删改查详解

Elena
Elena
发布时间:2026-10-13| 3人浏览过
原创

本文详细介绍如何在Python中使用pymongo库连接MongoDB数据库。内容涵盖MongoDB环境配置、数据插入、查询统计、排序偏移以及更新删除操作。重点解析了使用$set与不使用$set在更新数据时的字段保留差异,并提供完整的代码示例与结果分析,帮助开发者掌握Python与MongoDB的高效交互方法。

MongoDB作为当前主流的NoSQL数据库,采用BSON格式存储数据,其结构类似于JSON,便于处理复杂的数据类型。

1. 安装Mongodb和pymongo

首先需完成MongoDB的安装与基础配置。

具体的安装步骤可通过网络搜索获取,安装完成后需进行以下配置操作。

1.1 创建目录, 该目录为Mongodb数据文件的存放目录:

*注: 本人使用的不是root用户, 所以修改目录的拥有者. *


sudo mkdir /data
sudo chown -R python:python /data
mkdir /data/db

1.2 分别执行命令:

第一条命令用于指定服务端口及数据存储路径,第二条命令用于启动MongoDB数据库服务。


mongod --port 27017 --dbpath /data/db
mongo --port 27017

1.3 安装pymongo

sudo pip3 install pymongo

2. 连接数据库、指定数据库、指定集合、插入数据:

由于MongoDB以键值对形式存储数据,因此在Python中需通过定义字段来插入数据。


import pymongo
#连接mongodb
client = pymongo.MongoClient('mongodb://localhost:27017/')
#指定数据库
db = client.test4
#指定集合
collection = db.students
#数据
student1 = {
 'id': '201801',
 'name': 'Jack',
 'age': 20,
 'gender': 'male'
}
student2 = {
 'id': '201802',
 'name': 'Tom',
 'age': 22,
 'gender': 'male'
}
student3 = {
 'id': '201803',
 'name': 'Rose',
 'age': 21,
 'gender': 'female'
}
student4 = {
 'id': '201804',
 'name': 'Mike',
 'age': 20,
 'gender': 'female'
}
student5 = {
 'id': '201805',
 'name': 'Ray',
 'age': 20,
 'gender': 'female'
}
student6 = {
 'id': '201806',
 'name': 'Alan',
 'age': 21,
 'gender': 'male'
}
#插入一条数据
result1 = collection.insert_one(student1)
print(result1)
print(result1.inserted_id)
# #插入多条数据
result2 = collection.insert_many([student2, student3, student4, student5, student6])
print(result2)
print(result2.inserted_ids)

运行结果:

insert方法:

5b3a1942971951218d41c02b [ObjectId('5b3a1942971951218d41c02c'), ObjectId('5b3a1942971951218d41c02d')]

官方推荐:


<pymongo.results.InsertOneResult object at 0x7fa4cc363ec8>
5b3a1942971951218d41c02e
<pymongo.results.InsertManyResult object at 0x7fa4cc363f08>
[ObjectId('5b3a1942971951218d41c02f'), ObjectId('5b3a1942971951218d41c030')]

3. 查询、计数、排序、偏移:


import pymongo
from bson.objectid import ObjectId
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client.test4
collection = db.students
#查询一条数据
print('单条数据','='*50)
result = collection.find_one({'name': 'Jack'})
print(result)
print('多条数据','='*50)
#查询多条数据
for res in collection.find({'age': {'$mod': [5, 0]}}):
 print(res)
#计数
print('计数','='*50)
count = collection.find({'age': {'$mod': [5, 0]}}).count()
print(count)
#排序
print('排序','='*50)
results = collection.find().sort('name', pymongo.ASCENDING) #升序, pymongo.DESCENDING为降序
print([result['name'] for result in results])
#偏移
print('偏移','='*50)
results = collection.find().sort('name', pymongo.ASCENDING).skip(2) #偏移2位,忽略前两个数据
print([result['name'] for result in results])
results = collection.find().sort('name', pymongo.ASCENDING).skip(2).limit(2) #只输出2个数据
print([result['name'] for result in results])
find({‘age': {'$mod': [5, 0]}}): 表示查找年龄取余5余0的值. 还有很多比较符号, 请百度.

运行结果:


单条数据 ==================================================
{'_id': ObjectId('5b3a1942971951218d41c02b'), 'id': '201801', 'name': 'Jack', 'age': 20, 'gender': 'male'}
多条数据 ==================================================
{'_id': ObjectId('5b3a1942971951218d41c02b'), 'id': '201801', 'name': 'Jack', 'age': 20, 'gender': 'male'}
{'_id': ObjectId('5b3a1942971951218d41c02e'), 'id': '201804', 'name': 'Mike', 'age': 20, 'gender': 'female'}
{'_id': ObjectId('5b3a1942971951218d41c02f'), 'id': '201805', 'name': 'Ray', 'age': 20, 'gender': 'female'}
计数 ==================================================
3
排序 ==================================================
['Alan', 'Jack', 'Mike', 'Ray', 'Rose', 'Tom']
偏移 ==================================================
['Mike', 'Ray', 'Rose', 'Tom']
['Mike', 'Ray']

4. 更新:

4.1 不使用$set更新数据:


import pymongo
from bson.objectid import ObjectId
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client.test4
collection = db.students
#修改
condition = {'name': 'Jack'}
student = collection.find_one(condition) #获得满足condition的数据
print('更新前: ', student)
student['age'] = 22 #修改年龄
result = collection.update(condition, student) #将修改后的student替换condition
print('更新后', collection.find_one(condition))
#更新的返回值
print(result) #ok=1代表执行成功, nModified代表影响的条数

运行结果:


更新前: {'_id': ObjectId('5b3a1942971951218d41c02b'), 'id': '201801', 'name': 'Jack', 'age': 20, 'gender': 'male'}
更新后 {'_id': ObjectId('5b3a1942971951218d41c02b'), 'id': '201801', 'name': 'Jack', 'age': 22, 'gender': 'male'}
{'ok': 1, 'nModified': 1, 'n': 1, 'updatedExisting': True}

4.2 使用$set更新数据:


import pymongo
from bson.objectid import ObjectId
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client.test4
collection = db.students
#使用$set更新
condition = {'name': 'Jack'}
student = collection.find_one(condition) #获得满足condition的数据
print('更新前: ', student)
student['age'] = 23 #修改年龄
result = collection.update(condition, {'$set': student}) #将修改后的student替换condition, $set为重点
print('更新后', collection.find_one(condition))
#更新的返回值
print(result) #ok=1代表执行成功, nModified代表影响的条数

运行结果:


更新前: {'_id': ObjectId('5b3a1942971951218d41c02b'), 'id': '201801', 'name': 'Jack', 'age': 22, 'gender': 'male'}
更新后 {'_id': ObjectId('5b3a1942971951218d41c02b'), 'id': '201801', 'name': 'Jack', 'age': 23, 'gender': 'male'}
{'ok': 1, 'nModified': 1, 'n': 1, 'updatedExisting': True}

对比使用和不使用$set进行数据更新,在上述简单示例中两者表现无明显区别。

下面介绍区别所在:

4.3 区别


import pymongo
from bson.objectid import ObjectId
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client.test4
collection = db.students
#使用和不使用$set更新的区别
print('使用: ')
condition = {'name': 'Jack'}
student = collection.find_one(condition) #获得满足condition的数据
print('更新前: ', student)
student = {
 'id': '201803',
 'name': 'Jack',
 'age': 20,
 'gender': 'female',
 'mother': "Jack's mother"
}
result = collection.update(condition, {'$set': student}) #将修改后的student替换condition
print('更新后', collection.find_one(condition))
#更新的返回值
print(result) #ok=1代表执行成功, nModified代表影响的条数
#分割线
print()
print('='*20, '分割线', '='*20)
print()
print('不使用: ')
condition = {'name': 'Jack'}
student = collection.find_one(condition) #获得满足condition的数据
print('更新前: ', student)
student = {
 'id': '201803',
 'name': 'Jack',
 'age': 20,
 'gender': 'female',
 'father': "Jack's father"
}
result = collection.update(condition, student) #将修改后的student替换condition
print('更新后', collection.find_one(condition))
#更新的返回值
print(result) #ok=1代表执行成功, nModified代表影响的条数

运行结果:

使用:


更新前: {'_id': ObjectId('5b3a1942971951218d41c02b'), 'id': '201801', 'name': 'Jack', 'age': 23, 'gender': 'male'}
更新后 {'_id': ObjectId('5b3a1942971951218d41c02b'), 'id': '201803', 'name': 'Jack', 'age': 20, 'gender': 'female', 'mother': "Jack's mother"}
{'ok': 1, 'nModified': 1, 'n': 1, 'updatedExisting': True}

==================== 分割线 ====================


不使用: 
更新前: {'_id': ObjectId('5b3a1942971951218d41c02b'), 'id': '201803', 'name': 'Jack', 'age': 20, 'gender': 'female', 'mother': "Jack's mother"}
更新后 {'_id': ObjectId('5b3a1942971951218d41c02b'), 'id': '201803', 'name': 'Jack', 'age': 20, 'gender': 'female', 'father': "Jack's father"}
{'ok': 1, 'nModified': 1, 'n': 1, 'updatedExisting': True}

分析上述运行结果可知,使用$set进行更新时,若更新数据中包含原数据没有的字段,则会将该字段追加到原数据中(如上例新增mother字段),而不会删除原有字段。相反,若不使用$set,系统将从原数据中删除更新数据未包含的字段,再添加新字段(如上例删除mother字段并新增father字段,这实质上是将原数据完全替换为更新数据)。

4.4 update_one和update_many的区别:


import pymongo
from bson.objectid import ObjectId
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client.test4
collection = db.students
#官方推荐使用
#update_one和update_many的区别
print('update_one: ')
condition = {'age': {'$gt': 20}}
result = collection.update_one(condition, {'$inc': {'age': 1}})
print(result)
print(result.matched_count, result.modified_count)
#分割线
print()
print('='*20, '分割线', '='*20)
print()
print('update_many: ')
condition = {'age': {'$gt': 20}}
result = collection.update_many(condition, {'$inc': {'age': 1}})
print(result)
print(result.matched_count, result.modified_count)

运行结果:


update_one: 
<pymongo.results.UpdateResult object at 0x7f6cace0f9c8>
1 1
==================== 分割线 ====================
update_many: 
<pymongo.results.UpdateResult object at 0x7f6cace0fa88>
3 3
12345678910
{‘age': {'$gt': 20}}为查找年龄大于20的, {‘inc': {‘age': 1}}为将年龄+1

5. 删除:


import pymongo
from bson.objectid import ObjectId
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client.test4
collection = db.students
#删除
result = collection.remove({'name': 'Jack'})
print(result)
#推荐使用
result = collection.delete_one({'age': {'$gt': 20}})
print(result.deleted_count)
result = collection.delete_many({'age': {'$gt': 20}})
print(result.deleted_count)

运行结果:

{'ok': 1, 'n': 1} 1 2

6. 其他

除上述常用操作外,还包括find_one_and_delete()(查找后删除)和find_one_and_replace()(查找后替换)等方法,感兴趣者可进一步查阅官方文档或相关资料。

总结

以上所述是小编给大家介绍的Python与Mongodb数据库之间的操作方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对本站网站的支持! 如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。