MongoDB存储

1、链接MongoDB

       指定数据库

       指定集合

import pymongo

## 连接数据库
client = pymongo.MongoClient(host='localhost', port=27017)
## 指定数据库 kuluma
db = client.kuluma
## 指定集合
collection = db.mycol

  

2、数据库操作

①插入数据

## 插入数据
## insert_one 插入一条数据
student = {
'id':'190720157',
'name':'Amy',
'age':23,
'gender':'female'
}
result = collection.insert_one(student)
print(result) ## 返回 InsertOneResult 对象
print(result.inserted_id) ## 获取 MonggoDB 自动添加的标识符 _id :5ea5340ef3cd203fa1577e4e ## insert_many 插入多条数据
student1 = {
'id':'190720158',
'name':'Lily',
'age':18,
'gender':'female'
}
student2 = {
'id':'190720159',
'name':'Mark',
'age':20,
'gender':'male'
}
results = collection.insert_many([student1,student2])
print(results)
print(results.inserted_ids)

  

②查询

  ※find()得到一个生成器对象,需要循环遍历

## 查询多条数据
results = collection.find({'age':20})
for r in results:
print(r)

  

   ※find_one()得到单个结果,字典类型

## 查询 一条数据
result = collection.find_one({'name':'Amy'})
print(type(result)) ## <class 'dict'> 返回结果时字典类型
print(result)

  

  ※比较查询

## 查询年龄大于等于20的数据
result1 = collection.find({'age':{'$gte':20}})
for r in result1:
print(r)

  ※正则匹配

## 正则匹配查询
##查询以 M 开头的学生
result2 = collection.find({'name':{'$regex':'^M.*'}})
for r in result2:
print(r)

③计数

## 计数
count = collection.find().count()
print(count)

  

④排序

## 排序
s_sort = collection.find().sort('age',pymongo.ASCENDING)
print([s for s in s_sort]) ## 升序
j_sort = collection.find().sort('age',pymongo.DESCENDING)
print([j for j in j_sort]) ## 降序

  

⑤偏移

数据量过大,不建议使用偏移,可以对id_进行条件查询

## 偏移 跳过前两个查询结果,得到第三个以后的数据
skip = collection.find().sort('age',pymongo.ASCENDING).skip(2)
print([s['name'] for s in skip])
## limit(1) 限制只返回一个结果
limit= collection.find().sort('age',pymongo.ASCENDING).skip(2).limit(1)
print([l['name'] for l in limit])

  

最新文章

  1. 【翻译】首个基于NHibernate的应用程序
  2. Numpy 学习之路(1)——数组的创建
  3. 关于each
  4. unreal3的坐标系统和vector/rotator
  5. MFC中添加用户自定义消息
  6. repcached的安装练习
  7. Java基础-final变量和普通变量的区别
  8. CentOS7安装mysql-server
  9. FutureTask解析(转)
  10. CCF-201509-3-生成模板系统
  11. JDK动态代理[1]----代理模式实现方式的概要介绍
  12. Ubuntu 16.04安装Notepadqq编辑器替代Notepad++
  13. express 连接数据库
  14. week06 12 我们准备数据 前端调用rpc 前后端联调一下
  15. 命令行选项 - Mozilla 产品与私有技术 | MDN - Google Chrome
  16. java 网络编程(三)简单的即时通讯(UDP传输)
  17. c++中typedef、define、const、inline之间的区别
  18. http常见状态码有哪些?
  19. 82. Remove Duplicates from Sorted List II (List)
  20. Django——CBV与FBV

热门文章

  1. Seata分布式事务
  2. app实现外部浏览器打开链接
  3. appium连接手机 adb调试 app自动化
  4. P4525 【模板】自适应辛普森法 1
  5. JavaSE 对象与类(一)
  6. [EULAR文摘] 超声滑膜炎和腱鞘炎对已获临床缓解患者病情复发的预测
  7. CF884F - Anti-Palindromize
  8. LeetCode-475 供暖器
  9. Django-drf-序列化器高级用法之SerializerMethodField
  10. Android 删除已知路径的文件或文件夹