实例详解Python与Mongodb数据库之间的操作方法

  • 更新时间:2020-03-17 09:34:55
  • 编辑:池忆梅

MongoDB 是目前最流行的 NoSQL 数据库之一,使用的数据类型 BSON(类似 JSON)。

1. 安装Mongodb和pymongo

Mongodb的安装和配置

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 update函数定义及作用实例解析

    介绍了python update函数的定义及作用

    发布时间:2019-07-11

  • java 中mongodb的各种操作查询的实例详解

    这篇文章主要介绍了java 中mongodb的各种操作查询的实例详解的相关资料,希望通过本文能帮助到大家,需要的朋友可以参考下

    发布时间:2019-08-29

  • Python全栈数据工程师养成攻略(视频)

    Python全栈数据工程师养成攻略(视频)

    本书介绍了数据工程和Python语法,随后讲解如何获取和存储数据,并实现简单的静态可视化,帮助读者将学习到关于Web建站的一些基础和进阶知识

    大小:129.7 MBPython全栈电子书

  • Python机器学习算法

    Python机器学习算法

    这是一本机器学习入门读物,注重理论与实践的结合,以典型的机器学习算法为例,从算法原理出发,由浅入深,详细介绍算法的理论,并配合目前流行的Python语言,从零开始,增强实际的算法实践能力

    大小:30.1 MBPython机器学习电子书

  • Python游戏编程入门

    Python游戏编程入门

    本书为读者提供了充分的实践和练习,并且关注Python编程中的高级话题,这些全部通过游戏示例和项目来介绍,而这已经证明是一种高效而有趣的学习方法,感兴趣的可以了解一下

    大小:41.6 MBPython游戏编程电子书

  • Python编程无师自通

    Python编程无师自通

    Python编程无师自通 专业程序员的养成 零基础自学Python3入门教程 Python基础教程

    大小:122.4 MBPython编程电子书

  • Python机器学习

    Python机器学习

    Python机器学习中文版(Sebastian Raschka著),一共13章,含机器学习算法、模型评估、集成学习、web应用、神经网络等,想要学习机器语言的可以下载学习

    大小:42.1MBPython电子书

  • Python机器学习基础教程

    Python机器学习基础教程

    这是一本机器学习入门书,以Python语言介绍,包含机器学习的基本概念及其应用;实践中最常用的机器学习算法以及这些算法的优缺点;待处理数据的呈现方式的重要性等内容

    大小:28.3 MBPython电子书

  • Python高级编程(第2版)

    Python高级编程(第2版)

    Python作为一种高-级程序设计语言,本书于Python 3.5版本进行讲解,深度揭示了Python编程的高级技巧,适合想要进一步提高自身Python编程技能的读者阅读,也适合对Python编程感兴趣的读者参考学习

    大小:76.8 MBPython编程电子书

  • 零起点Python机器学习快速入门

    零起点Python机器学习快速入门

    这本书采用独创的黑箱模式,MBA案例教学机制,结合一线实战案例,介绍Sklearn人工智能模块库和常用的机器学习算法,读完本书内容和配套的教学代码,就能够编写简单的机器学习函数

    大小:85.1 MBPython机器学习电子书

  • Python数据分析入门:从数据获取到可视化

    Python数据分析入门:从数据获取到可视化

    它是1本实干之作,集中体现数据统计分析步骤的各类阶段,包括统计数据的收集、清理和探索性剖析,并根据大伙儿耳熟能说的Python小工具多方面实际操作。 这书做为数据统计分析的新手入门

    大小:5.4 MBPython电子书

用户留言