pymongo操作MongoDB基础教程


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

MongoDB安装:

因为我已经安好了…等我下次安的时候再自己出教程吧🔮

pymongo安装

pip install pymongo

MongoDB启动:

需要以管理员身份运行cmd

NET start MongoDB

在这里插入图片描述

连接数据库:

import pymongo
client = pymongo.MongoClient(host="localhost", port=27017)

等价方法:

client = pymongo.MongoClient('mongodb://localhost:27017/')

获取服务器上所有数据库名称:

dblist=client.list_database_names()

指定数据库:

db = client.test

等价方法:

db = client['test']

如果该数据库存在,则在该数据库上继续操作;
若该数据库不存在,则新建一个数据库进行操作(注意,这里新建了一个新的数据库后并不会马上显示,比如你在新建了一个数据库后就立刻去查看dblist会发现是没有这个新库名称的,只有等到你对这个数据库添加东西了以才会显示出来)

指定集合:

collection = db.students

等价方法:

collection = db['students']

同理,
如果该集合存在,则在该集合上继续操作;
若该集合不存在,则新建一个数集合进行操作(注意,这里新建了一个新的集合后并不会马上显示,只有等到你对这个集合添加东西了以才会显示出来)

插入:

插入一条数据:

result = collection.insert(student1)
print(result)

在这里插入图片描述
在这里插入图片描述
这里飙红是因为版本不一致,虽然不影响,但是还是看他不爽。

用它建议的方法实现:

student1 = {
    'name': 'student1',
    'age': 20,
}
result = collection.insert_one(student1)
print(result)

在这里插入图片描述
(我把上面建的那个删了,又重新添加的,得到了一样的结果)
在这里插入图片描述

插入多条数据:

results = collection.insert([student2,student3])
print(results)

在这里插入图片描述
在这里插入图片描述
删掉新数据后用它建议的方法:

student2 = {
    'name': 'student2',
    'age': 23,
}
student3 = {
    'name': 'student3',
    'age': 17,
}
results = collection.insert_many([student2,student3])
print(results)

在这里插入图片描述
在这里插入图片描述

查看插入数据的id:

print(result.inserted_id)
print(results.inserted_ids)

在这里插入图片描述
在这里插入图片描述

查找:

查找单个结果:

根据普通属性查询:

result = collection.find_one({'name': 'student1'})
print(type(result))
print(result)

在这里插入图片描述

根据ObjectId查询:

需要先:

from bson import ObjectId
result = collection.find_one({'_id': ObjectId('5e91c769e134b49160dc4ee4')})
print(type(result))
print(result)

在这里插入图片描述

查找多个结果:

(在这之前,我先又添加一个了年龄和student3一样的student4)
在这里插入图片描述

普通查询:

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

在这里插入图片描述

条件查询:

条件查询将要查询的value也变成了一个字典,这个小字典的key是查询符号,value是条件

比如查询年龄大于18的人:

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

在这里插入图片描述
这里的{'$gt':18}就是大于18的意思,$gt就是大于的意思。

这里还有一些常用的查询符号:

符号含义示例
$lt小于{‘age’: {’$lt’:18}}
$gt大于{‘age’: {’$gt’:18}}
$lte小于等于{‘age’: {’$lte’:18}}
$gte大于等于{‘age’: {’$gte’:18}}
$ne不等于{‘age’: {‘ne’:18}}
$in在范围内{‘age’: {’$in’:[18,20]}}
$nin不在范围内{‘age’: {’$nin’:[18,20]}}

正则匹配查询:$regex
例如正则匹配名字最后一位为0-2的人:

results = collection.find({'name': {'$regex':'[0-2]$'}})
print(type(results))
print(results)
for result in results:
    print(result)

在这里插入图片描述
还有许多查询方式如:

符号含义示例示例含义
$exists属性是否存在{‘name’:{’$exists’:True}}name属性存在
$type类型判断{‘age’:{’$type’:‘int’}}age为int类型
$mod数字取模{‘age’:{’$mod’:[5,0]}}年龄模5等于0
$text文本查询{’KaTeX parse error: Expected '}', got 'EOF' at end of input: text':{'search’:‘student’}}text类型的属性中包含student字符串
$where高级条件查询{’$where’: “obj.age >= 17”}查询年龄大于等于17的人(其实$where能做的远远不止这么点)

偏移:

比如,我对姓名排序后,不想要前两个,就可以用skip偏移两位:

results = collection.find().sort('name').skip(2)
print([_['name'] for _ in results])

在这里插入图片描述
但是,如果数据量非常大的话(千万亿级别),尽量不要使用skip,这样做可能会导致内存溢出。

可以利用符号$查询配合ObjectId来完成:

比如我想偏移两位:

results = collection.find({'_id': {'$gt': ObjectId("5e91c769e134b49160dc4ee5")}})
print([_['name'] for _ in results])

在这里插入图片描述

限制个数:

如果find获得的数据太多,可以用limit做限制:

results = collection.find().sort('name').limit(2)
print([_['name'] for _ in results])

默认取前n位
在这里插入图片描述

计数:

统计所有数据量:

count = collection.find().count()
print(count)

在这里插入图片描述
同样,pymongo已经不推荐这种写法了,我们用他推荐的看看:

count = collection.count_documents
print(count)

在这里插入图片描述

统计想要查询的数据量:

count = collection.find({'age': 17}).count()
print(count)

在这里插入图片描述

count = collection.count_documents({'age': 17})
print(count)

在这里插入图片描述

排序:

升序:

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

在这里插入图片描述

降序:

results = collection.find().sort('name', pymongo.DESCENDING)
print([_['name'] for _ in results])

在这里插入图片描述

条件排序:

这里对年龄大于17的人的姓名进行排序(默认升序)

results = collection.find({'age': {'$gt': 17}}).sort('name')
print([_['name'] for _ in results])

在这里插入图片描述

更新:

更新所有数据:

在这里插入图片描述

condition = {'name': 'student4'}
student = {'name': 'update_student4'}
result = collection.update(condition, student)
print(result)

在这里插入图片描述
在这里插入图片描述
可以看到,这里将student4的内容替换成了student字典。

解决这个看他不顺眼的报错:

用它推荐的方式改回来:

condition = {'name': 'update_student4'}
student = {'name': 'student4', 'age': 17}
result = collection.replace_one(condition, student)
print(result)

在这里插入图片描述
在这里插入图片描述

更新部分数据:

比如我只想更新student4的name:
在这里插入图片描述

condition = {'name': 'student4'}
student = collection.find_one(condition)
student['name'] = 'update_student4'
result = collection.update(condition, student)
print(result)

在这里插入图片描述
在这里插入图片描述
用他建议的方式改回来:

condition = {'name': 'update_student4'}
student = collection.find_one(condition)
student['name'] = 'student4'
result = collection.replace_one(condition, student)
print(result)

在这里插入图片描述
在这里插入图片描述
还有一种更新的方式:$set
在这里插入图片描述

condition = {'name': 'student4'}
student = {'name': 'set_student4'}
result = collection.update(condition, {'$set': student})
print(result)

在这里插入图片描述
在这里插入图片描述
用它建议的方式改回来:

condition = {'name': 'set_student4'}
result = collection.update_one(condition, {'$set': {'name': 'student4'}})
print(result)

在这里插入图片描述
在这里插入图片描述
上面使用了update_one修改了一个内容,可以使用update_many修改多个内容:

condition = {'name': 'student4'}
result = collection.update_many(condition, {'$set': {'name': 'set_student4', 'age': 100}})
print(result)

在这里插入图片描述
在这里插入图片描述

删除:

result = collection.remove( {'name': 'set_student4', 'age': 100})
print(result)

在这里插入图片描述
在这里插入图片描述
用它推荐的方法:

删除一条:

result = collection.delete_one({'name': 'student3'})
print(result)

在这里插入图片描述
在这里插入图片描述

删除多条:

比如我用正则匹配删除剩余两条数据:

result = collection.delete_many({'name': {'$regex': '[1-2]$'}})
print(result)

在这里插入图片描述
在这里插入图片描述

组合方法:

查找后删除:find_one_and_delete
查找并更新:find_one_and_replace
查找并替换:find_one_and_update

用法和上面差不多,我就不举例了,大家可以试试

MongoDB关闭:

NET stop MongoDB

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值