1.连接mongodb

#########  方法一  ##########
import pymongo
# MongoClient()返回一个mongodb的连接对象client
client = pymongo.MongoClient(host="localhost",port=27017) ######### 方法二 ##########
import pymongo
# MongoClient的第一个参数host还可以直接传MongoDB的连接字符串,以mongodb开头
client = pymongo.MongoClient(host="mongodb://127.0.0.1:27017/")

2.指定数据库

######  方法一  ######
# 指定test数据库
db = client.test ###### 方法二 ######
# 指定test数据库(调用client的test属性即可返回test数据库)
db = client["test"]

3.指定集合

######  方法一  ######
# 指定student集合
collection = db.student ###### 方法二 ######
# 指定student集合
collection = db["student"]

4.插入数据

  • db.collection.insert()
    可以插入一条数据(dict),也可以插入多条数据(list),返回‘_id’或‘_id’的集合
###### 插入一条数据 ######
student = {
'name': 'Jordan',
'age': 18,
'gender': 'man'
} result = db.collection.insert(student)
# insert()返回执行后文档的主键'_id'的值
print(result) # 5932a68615c2606814c91f3d ###### 插入多条数据 ######
student1 = {
'name': 'Jordan',
'age': 10,
'gender': 'man'
} student2 = {
'name': 'Mike',
'age': 11,
'gender': 'man'
} result = collection.insert([student1,student2])
# insert()返回执行后文档的主键'_id'的集合
print(result) #[ObjectId('5932a80115c2606a59e8a048'), ObjectId('5932a80115c2606a59e8a049')]

pymongo 3.x版本中,insert()方法官方已不推荐使用,推荐使用insert_one()insert_many()将插入单条和多条记录分开。

  • db.collection.insert_one()
    用于插入单条记录,返回的是InsertOneResult对象
student = {
'name': 'Jordan',
'age': 18,
'gender': 'man'
} result = collection.insert_one(student)
# insert_one()返回的是InsertOneResult对象,我们可以调用其inserted_id属性获取_id。
print(result) # <pymongo.results.InsertOneResult object at 0x10d68b558>
print(result.inserted_id) # 5932ab0f15c2606f0c1cf6c5
  • db.collection.insert_many()
    用于插入多条记录,返回的是InsertManyResult对象
student1 = {
'name': 'Jordan',
'age': 10,
'gender': 'man'
} student2 = {
'name': 'Mike',
'age': 11,
'gender': 'man'
} result = collection.insert_many([student1, student2])
# insert_many()方法返回的类型是InsertManyResult,调用inserted_ids属性可以获取插入数据的_id列表
print(result) # <pymongo.results.InsertManyResult object at 0x101dea558>
print(result.inserted_ids) # [ObjectId('5932abf415c2607083d3b2ac'), ObjectId('5932abf415c2607083d3b2ad')]

5.查询数据:find_one()、find()

  • db.collection.find_one()
    查询返回单个结果(dict或者None)
result = db.collection.find_one({"name": "Mike"})
print(result) #{'_id': ObjectId('5932a80115c2606a59e8a049'),'name': 'Mike', 'age': 21, 'gende' :'man'} db.collection.find()
查询返回多个结果(cursor类型,可迭代)。
results = collection.find({"age":18})
print(results) # <pymongo.cursor.Cursor object at 0x1032d5128>
for result in results:
print(result)
#
  • 查询条件

 
  • 多条件查询 $and $or
# and查询
db.collection.find({
$and : [
{ "age" : {$gt : 10 }} ,
{ "gender" : "man" }
]
}) #or查询
db.collection.find({
$or : [
{"age" : {$gt : 10 }},
{ "gender" : "man"}
]
}) #and查询 和 or查询
db.inventory.find( {
$and : [
{ $or : [ { price : 0.99 }, { price : 1.99 } ] },
{ $or : [ { sale : true }, { qty : { $lt : 20 } } ] }
]
} )
  • count()
    计数,对查询结果进行个数统计
count = collection.find().count()
print(count)
  • 排序 sort()
    调用sort方法,传入要排序的字段and升降序标志即可
#单列升序排列
results = db.collection.find().sort('name', pymongo.ASCENDING) # 升序(默认)
print([result['name'] for result in results]) # 单列降序排列
results = db.collection.find().sort("name",pymongo.DESCENDING) #降序
print([result['name'] for result in results]) #多列排序
results = db.collection.find().sort([
("name", pymongo.ASCENDING),("age", pymongo.DESCENDING)
])
  • 偏移 skip()
results = collection.find().sort('name', pymongo.ASCENDING).skip(2)
print([result['name'] for result in results])

注意:在数据量非常庞大时(千万、亿级别),最好不要用skip()来查询数据,可能导致内存溢出。可以使用
find({'_id': {'$gt': ObjectId('593278c815c2602678bb2b8d')}})
这样的方法来查询。

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

6.更新数据

  • db.collection.update()
    修改单条或者多条文档,已不推荐此用法
result = collection.update(
{"age": {"$lt" : 15}} ,
{"$set" : {"gender" : "woman"}}
) print(result) # {'ok': 1, 'nModified': 1, 'n': 1, 'updatedExisting': True}
  • db.collection.update_one()
    修改单条文档,返回结果是UpdateResult类型

针对UpdateResult类型数据,可以调用matched_count和modified_count属性分别获取匹配的条数和影响的条数

result = db.collection.update_one(
{"name" : "Mike"} ,
{
"$inc" : {"age" : 5},
"$set": {"gender": "male"}
}
) print(result) # <pymongo.results.UpdateResult object at 0x10d17b678> print(result.matched_count, result.modified_count) # 1 1
  • db.collection.update_many()
    修改多条文档,返回结果是UpdateResult类型
result = db.collection.update_many(
{"name" : "Mike"} ,
{"$inc" : {"age" : 5}}
) print(result) # <pymongo.results.UpdateResult object at 0x10c6384c8> print(result.matched_count, result.modified_count) # 3 3

7.删除数据

  • db.collection.remove()
    删除指定条件的所有数据
result = db.collection.remove({"age" : {"$gte" : 10}})

print(result)  # {'ok': 3, 'n': 3}
  • db.collection.delete_one()
    删除第一条符合条件的数据,返回DeleteResult类型数据
result = collection.delete_one({'name': 'Kevin'})
print(result) # <pymongo.results.DeleteResult object at 0x10e6ba4c8>
print(result.deleted_count) #
  • db.collection.delete_many()
    删除所有符合条件的数据,返回DeleteResult类型数据
result = collection.delete_many({'name': 'Kevin'})
print(result) # <pymongo.results.DeleteResult object at 0x55e6be5f1>
print(result.deleted_count) #

另外,pymongo还提供了更多方法,如find_one_and_delete() find_one_and_replace() find_one_and_update(),当然,还有操作索引的方法:create_index() create_indexes() drop_index()等。

import pymongo

client = pymongo.MongoClient(host="127.0.0.1", port="")

db = client["test"]
coll = db["myindex"] # 在后台创建唯一索引
coll.create_index([(x,1)], unique = True, background = True,name = "x_1") # 查看集合coll的所有索引信息
result = coll.index_information()
print(result) # 在后台创建复合索引
db.myindex.create_index([("x", 1), ("y", 1)]) # 删除索引
coll.drop_index([("x", 1)])
# coll.drop_index("x_1")

详细用法可以参见官方文档:http://api.mongodb.com/python/current/api/pymongo/collection.html

另外还有对数据库、集合本身以及其他的一些操作,在这不再一一讲解,可以参见官方文档:http://api.mongodb.com/python/current/api/pymongo/

最新文章

  1. 算法系列:Fibonacci
  2. R语言多项式回归
  3. 第十六回 IoC组件Unity续~批量动态为Unity添加类型和行为
  4. MySQL5.7.13源代码阅读心得
  5. 李洪强-C语言4-内存分析
  6. jmeter随笔(4)--中文url编码问题
  7. php 检查email电子邮件函数(奇葩写法)
  8. 框架优化系列文档:SVN中非版本控制文件忽略上传的设置
  9. pomelo组件..
  10. 使用Cloudsim实现基于多维QoS的资源调度算法之中的一个:配置Cloudsim环境
  11. BZOJ 4503 两个串(FFT)
  12. 一旦ORA-28000: the account is locked用户锁定故障排除
  13. EL函数和自定义EL函数
  14. WebRoot 与 webContent的区别
  15. Maven配置ojdbc14-10.2.0.4.0.jar
  16. VS2017开发的IDE扩展
  17. 那些年读过的书《Java并发编程实战》二、如何设计线程安全类
  18. solr 打分和排序机制(转载)
  19. 【IT笔试面试题整理】二叉树中和为某一值的路径--所有可能路径
  20. 封装naive socket

热门文章

  1. redis命令之 ----String(字符串)
  2. 微博Feed流
  3. PHP导出文件到csv函数
  4. python 手机app数据爬取
  5. Java生鲜电商平台-商品无限极目录的设计与架构
  6. 2019 奥买家java面试笔试题 (含面试题解析)
  7. JavaScript调用百度地图
  8. FFT之频率与幅值的确定(转)
  9. maven 学习---Maven自动化部署
  10. authenticating with the app store 一直卡住--问题记录