1. 安装MongoDB并启动服务,安装PyMongo
2. 连接MongoDB,并指定连接数据库、集合

import pymongo

client = pymongo.MongoClient(host='localhost', port=27017)
client = MongoClient('mongodb://localhost:27017/') db = client.test
db = client['test'] collection = db.students
collection = db['students']

3. 插入

student = {
'id': '20170101',
'name': 'Jordan',
'age': 20,
'gender': 'male'
}
'''
result = collection.insert(student)
print(result) #5932a68615c2606814c91f3d
result = collection.insert([student, student])
print(result) #[ObjectId('5932a80115c2606a59e8a048'), ObjectId('5932a80115c2606a59e8a049')]
'''
#PyMongo 3.x版本中推荐使用 insert_one、insert_many
result = collection.insert_one(student)
print(result.inserted_id)
result = collection.insert_many([student, student])
print(result.inserted_ids)

4. 查询

result = collection.find_one({'name': 'Mike'})
print(type(result)) #<class 'dict'>
print(result) from bson.objectid import ObjectId
result = collection.find_one({'_id': ObjectId('593278c115c2602667ec6bae')}) #查询指定id结果
print(result) results = collection.find({'age': 20}) #等值查询
results = collection.find({'age': {'$gt': 20}}) #大于20
results = collection.find({'name': {'$regex': '^M.*'}}) #正则,M开头
print(results) #cursor对象,相当于生成器
for result in results:
print(result)

5. 计数

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

6. 排序

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

7. 偏移

''' 忽略前N个元素,取几条

注意:在数据库数量非常庞大的时候,如千万、亿级别,最好不要使用大的偏移量来查询数据,
因为这样很可能导致内存溢出。最好记录上次_id用条件查询
'''

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

8. 更新

'''
首先指定查询条件,然后将数据查询出来,修改年龄后调用update()方法将原条件和修改后的数据传入。
condition = {'name': 'Kevin'}
student = collection.find_one(condition)
student['age'] = 25
result = collection.update(condition, student)
print(result) #{'ok': 1, 'nModified': 1, 'n': 1, 'updatedExisting': True} 这样可以只更新student字典内存在的字段。如果原先还有其他字段,则不会更新,也不会删除。
而如果不用$set的话,则会把之前的数据全部用student字典替换;如果原本存在其他字段,则会被删除。
result = collection.update(condition, {'$set': student})
''' # 推荐使用
condition = {'name': 'Kevin'}
student = collection.find_one(condition)
student['age'] = 26
result = collection.update_one(condition, {'$set': student}) condition = {'age': {'$gt': 20}}
result = collection.update_one(condition, {'$inc': {'age': 1}}) #年龄+1
#result = collection.update_many(condition, {'$inc': {'age': 1}})
print(result)
print(result.matched_count, result.modified_count)

9. 删除

'''result = collection.remove({'name': 'Kevin'})  #符合条件的所有记录'''
#推荐使用
result = collection.delete_one({'name': 'Kevin'})
result = collection.delete_many({'age': {'$lt': 25}})
print(result)
print(result.deleted_count)

10. 其他组合方法

create_index、create_indexes、drop_index
find_one_and_delete、find_one_and_replace、find_one_and_update

 

参考链接:

官方文档

转自:Python操作MongoDB看这一篇就够了

最新文章

  1. java3
  2. DataTables 控件使用和心得 (2) - 参数Options
  3. Could not link against boost_system 解决办法
  4. LVS四种实现模式详解
  5. [daily][network] NAT原理(转)
  6. Object-C: 枚举
  7. nginx 配置.json文件直接访问
  8. Style 的优先级
  9. JS 操作URL(重要)
  10. JS笔记1
  11. BZOJ 1305 CQOI2009 dance跳舞 二分答案+最大流
  12. HDU-5123-who is the best?
  13. jquery 中时间的运用
  14. ASP.NET MVC 3 笔记
  15. AngularJS中使用Karma单元测试初体验
  16. ALTER SEQUENCE 导致 REPLICAT 延时
  17. JS中如何处理多个ajax并发请求?
  18. Android之旅 自我图示总结四大组件
  19. DIV,CSS学习
  20. jquery datagrid设置pageSize不起作用

热门文章

  1. AtCoder Beginner Contest 140
  2. Paper | Non-local Neural Networks
  3. 使用Runtime的objc_copyClassNamesForImage和objc_getClassList获取类
  4. 前端笔记之Vue(三)生命周期&amp;CSS预处理&amp;全局组件&amp;自定义指令
  5. 【Oracle命令】sql语句之排序(order by)
  6. 获取系统相关信息 (CPU使用率 内存使用率 系统磁盘大小)
  7. SSD与HDD、HHD的区别
  8. tensorflow查看使用的是cpu还是gpu
  9. Jenkins 有关 Maven 的内容
  10. C#排序案例