pymongo方法详解
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/
pymongo方法详解的更多相关文章
- session的使用方法详解
session的使用方法详解 Session是什么呢?简单来说就是服务器给客户端的一个编号.当一台WWW服务器运行时,可能有若干个用户浏览正在运正在这台服务器上的网站.当每个用户首次与这台WWW服务器 ...
- Kooboo CMS - Html.FrontHtml[Helper.cs] 各个方法详解
下面罗列了方法详解,每一个方法一篇文章. Kooboo CMS - @Html.FrontHtml().HtmlTitle() 详解 Kooboo CMS - Html.FrontHtml.Posit ...
- HTTP请求方法详解
HTTP请求方法详解 请求方法:指定了客户端想对指定的资源/服务器作何种操作 下面我们介绍HTTP/1.1中可用的请求方法: [GET:获取资源] GET方法用来请求已被URI识别的资源.指定 ...
- ecshop后台增加|添加商店设置选项和使用方法详解
有时候我们想在Ecshop后台做个设置.radio.checkbox 等等来控制页面的显示,看看Ecshop的设计,用到了shop_config这个商店设置功能 Ecshop后台增加|添加商店设置选项 ...
- (转)Spring JdbcTemplate 方法详解
Spring JdbcTemplate方法详解 文章来源:http://blog.csdn.net/dyllove98/article/details/7772463 JdbcTemplate主要提供 ...
- C++调用JAVA方法详解
C++调用JAVA方法详解 博客分类: 本文主要参考http://tech.ccidnet.com/art/1081/20050413/237901_1.html 上的文章. C++ ...
- windows.open()、close()方法详解
windows.open()方法详解: window.open(URL,name,features,replace)用于载入指定的URL到新的或已存在的窗口中,并返回代表新窗口的Win ...
- CURL使用方法详解
php采集神器CURL使用方法详解 作者:佚名 更新时间:2016-10-21 对于做过数据采集的人来说,cURL一定不会陌生.虽然在PHP中有file_get_contents函数可以获取远程 ...
- JAVA 注解的几大作用及使用方法详解
JAVA 注解的几大作用及使用方法详解 (2013-01-22 15:13:04) 转载▼ 标签: java 注解 杂谈 分类: Java java 注解,从名字上看是注释,解释.但功能却不仅仅是注释 ...
随机推荐
- Entity Framework 6 中如何获取 EntityTypeConfiguration 的 Edm 信息?(四)
经过上一篇,里面有测试代码,循环60万次,耗时14秒.本次我们增加缓存来优化它. DbContextExtensions.cs using System; using System.Collectio ...
- ocelot性能测试
网上搜索发现多篇文章指出ocelot的性能有问题,可是在ocelot项目issue提问中,维护者指出,ocelot的性能问题不大.瓶颈在于.net的httpclient. 我参考文章 https:// ...
- 解决 Visual Studio 符号加载不完全问题
解决 Visual Studio 符号加载不完全问题 工具 - 选项 - 搜索 "符号" - 选上服务器 | 加载所有符号, 之后符号就会显示完全
- SAP MM模块相关透明表收集
物料表 MCHA 批次表(批次.评估类型 工厂物料) MARA 查看物料数据(发票名称.创建时间.人员) MARC 物料数据查询(利润中心.状态.在途) MAKT 查看物料描述 MKPF 物料抬头 M ...
- WPF xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
<Button Grid.Row="1" Content="Load Data" BorderBrush="Black" Border ...
- WPF-控件模板
说起控件模板,还是因为在一次需求实现中,我碰到了一个圆形按钮.一开始我认知的按钮是方形灰不拉几的一个块儿.这如何实现一个圆形按钮? 我最先想到的是使用样式,可是发现根本就没有改变Button形状的属性 ...
- Celery 异步队列
Celery Celery是一个功能完备即插即用的异步任务队列系统.它适用于异步处理问题,当发送邮件.或者文件上传, 图像处理等等一些比较耗时的操作,我们可将其异步执行,这样用户不需要等待很久,提高用 ...
- 在centos7 中docker info报错docker bridge-nf-call-iptables is disabled 的解决方法
在centos7中安装好docker以后,启动成功,运行命令 docker info ,报错: [root@iz2ze2bn5x2wqxdeq65wlpz ~]# docker info Client ...
- Scrum冲刺第三篇
一.每日例会 会议照片 成员 昨日已完成的工作 今日计划完成的工作 工作中遇到的困难 陈嘉欣 撰写博客,管理成员提交代码 每日博客,根据队员代码问题更改规范文档安排后续工作 队员提交的代码管理困难 邓 ...
- sparkSQL中的example学习(3)
UserDefinedTypedAggregation.scala(用户可自定义类型) import org.apache.spark.sql.expressions.Aggregator impor ...
