python操控——MongoDB数据库

目录

一、非关系型数据库

二、 链接MongoDB数据库

三、 指定一个非关系型数据库

四、 指定集合

五、插入数据

六、 查询数据

七、 计数

八、 排序

九、 偏移

十、更新

十一、 删除


一、非关系型数据库

NoSQL,全称为Not Only SQL,意思是不仅仅是SQL,繁殖非关系型数据库。NoSQL是基于键值对的,而且不需要经过SQL层的解析,数据间没有耦合性,性能非常高。

谈到NoSQL,其分类主要有:

键值存储数据库: 代表有Redis,Voidemort和Oracle BDB等。

列存储数据库: 代表有Cassandra,HBase和Riak等你

文档型数据库: 代表有CouchDB和MongoDB等。

图形数据库: 代表有Neo4j,InfoGrid和Infinite Graph等。

其中MongoDB是由C++语言编写的非关系型数据库,是一个基于分布式文件存储的开源数据库系统,其内容的储存形式类似JSON对象,它的字段值可以包含其他文档,数组及文档数组,非常灵活。

在使用MongoDB数据库之前,需要使用Pip3下载pymongo第三方库。

二、 链接MongoDB数据库

链接MongoDB数据库时,要使用PyMongo第三方库的MongoCLient方法,一般而言,传入MongoDB的IP和端口即可。MongoClient方法的第一个参数是地址host,第二个参数是端口port(默认值是27017)

例如,这里介绍两种连接MongoDB的连接方法:

import pymongo
​
client = pymongo.MongoClient(host='localhost',port=27017)#构造一个MongoDB连接对象
#也可以给host传递一个类似URL的字符串,也可以达到连接的效果
client = pymongo.MongoClient('mongodb://localhost:27017/')

三、 指定一个非关系型数据库

对数据库进行增删改查等操作之前,需要先指定其中一个数据库:

以下两种方法是等价的

db = client.school 
db = client['school']

四、 指定集合

MongoDB的每一个数据库又都包含许多集合,collection,这些集合类似于关系型数据库中的表。指定数据库之后,具体的操作是在集合上进行,则需要指定某一个集合。

#指定集合
collection = db.grade_1_1
collection = db['grade_1_1']

五、插入数据

在python3中,官方支持insert_one和insert_many两种方法,插入一条河多条数据。

插入单条数据:

#插入数据
student = {
    'id':'2185997',
    'name': 'Jordan',
    'age': 25,
    'gender':'male'
}
result = collection.insert_one(student)
print(result)
print(result.inserted_id)  #可以得到插入数据的id

插入多条数据,需要以列表的形式插入:

student1 = {
    'id':'2185997',
    'name': 'Jordan',
    'age': 25,
    'gender':'male'
}
​
student2 = {
    'id': '5659659',
    'name': 'Jhgfh',
    'age': 25,
    'gender': 'female'
}
result = collection.insert_many([student1,student2])
print(result)
print(result.inserted_ids)  #可以得到插入数据的id

不同的是使用inserted_ids返回插入数据的id。

六、 查询数据

MongoDB可以使用find方法查询数据。而在Python中则可以使用find_one和find两种方法进行查询,前者返回一条数据,后者可以返回一个生成器对象:

result = collection.find_one({'name':'chen'})  #查询姓名为chen的学生
print(type(result))
print(result)
​
结果:
<class 'dict'>
{'_id': ObjectId('64b8a918af1800006e0008e2'), 'id': '2145205', 'name': 'chen', 'age': 7.0, 'gender': 0.0}

'_id': ObjectId('64b8a918af1800006e0008e2')这个属性是MongoDB在插入数据时自动添加的。当然,也可以使用ObjectID来查询数据,此时需要使用bson库里的objectid:

from bson.objectid import ObjectId
​
result = collection.find_one({'_id': ObjectId('64b8a918af1800006e0008e2')})
print(result)

如果要查询多条记录,则可以使用find()方法:

results = collection.find({'age':25})
for result in results:
    print(result)

也可以使用运算符查询,比如查询年龄大于20岁的学生:

results = collection.find({'age':{'$gt':20}})
for result in results:
    print(result)

除了运算符以外,还有一些功能符号:

运算符:

$lt:小于

$gt: 大于

$lte: 小于等于

$gte: 大于等于

$ne: 不等于

$in: 在范围内 写法为:{'age':{'$in':[20,30]}}

$nin: 不在范围内 写法为:{'age':{'$nin':[20,30]}}

功能符:

$regex: 匹配正则表达式 {'name':{'$regex':'^M.*'}} 匹配name以M开头

$exists: 属性是否存在 {'name':{'$exists': True}} 存在name属性

$type: 类型判断 {'age':{'$type':'int'}} age的类型为int

$mod: 数字模运算 {'age':{'$mod':'[5,0]'}} age模5余0

$text: 文本查询 {'$text':{'$search':'Mike'}} text类型的属性中包含Mike的字符串

$where: 高级条件查询 {'$where':'obj.fans_count == obj.follows_count'} fans_count 与follows_count相等

七、 计数

统计集合中所有数据的个数,可以使用estimated_document_count()方法,不需要使用find方法:

count = collection.estimated_document_count()
print(count)

如果要统计查询结果的个数,则可以使用count_documents方法

db_count = collection.count_documents({'age':{'$gt': 20}})
print(db_count)

八、 排序

直接调用sort方法,传入排序的字段和升降序标志即可:

results = collection.find().sort('age',pymongo.ASCENDING)
print([result['name'] for result in results])

pymongo.ASCENOING代表升序排序,而pymongo.DESCENDING则代表降序排序。

九、 偏移

有的时候,如果只想要得到某几个元素,可以使用skip偏移几个位置,例如使用skip(2)则忽略前两个元素,从第三个元素开始输出。同时使用limit()方法可以限制得到的元素个数。

示例:

results = collection.find().sort('age',pymongo.ASCENDING).skip(1).limit(1)
print([result['name'] for result in results])

十、更新

对于数据更新,使用update方法,在其中指定更新的条件和更新后的数据即可。

官方给的更新方法有单独的update_one方法和update_many方法来处理单条或者多条更新过程,它们的第二个参数都需要使用$类型操作符作为字典的键名。

condition = {'name':'chen'}
student = collection.find_one(condition)
student['age'] = 26 #更新后的数据
result = collection.update_one(condition,{'$set':student})
print(result)
print(result.matched_count,result.modified_count)

matched_count属性是匹配的数据条数,

modified_count属性是影响的数据条数

更新多条数据:

condition = {'age':25}
result = collection.update_many(condition,{'$inc':{'age':1}})
print(result)
print(result.matched_count,result.modified_count)

'$inc':{'age':1}是让年龄加一。

十一、 删除

删除操作调用remove方法。但是官方推荐的两个方法是delete_one和delete_many。delete_one即删除第一条符合条件的数据,delete_many即删除所有符合条件的数据。

示例:

condition_one = {'name':'chen'}
condition_many = {'age':26}
result_one = collection.delete_one(condition_one)
print(result_one,result_one.deleted_count)
result_many = collection.delete_many(condition_many)
print(result_many,result_many.deleted_count)

deleted_count属性是被删除的数据条数。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值