崔庆才python3爬虫-pymongo


MongoDB存储

[官方文档](http://api.mongodb.com/python/current/api/pymongo/
collection.html)

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

准备工作

安装好pymongo并启动服务

1
2
3
4
5
6
7
1.打开mongodb的安装位置,如:E:\web-software\mongo\bin

2.打开终端黑窗口,输入:mongod --dbpath E:\web-software\mongo\bin   注意:不要关闭这个窗口

3.打开一个新的终端窗口,输入:mongo

此时,mongodb已经成功开启了,可以输入类似于show dbs之类的命令了。

连接MongoDB

1
2
3
4
import pymongo
client = pymongo.MongoClient(host='localhost', port=27017)
等同于
client = MogoClient('mongodb://localhost:27017/')

指定数据库

1
2
3
db = client.数据库名
等同于
db = client['数据库名']

指定集合

1
2
3
collection = db.集合名
等同于
collection = db['集合名']

插入数据

insert()

1
2
3
4
5
6
7
8
9
10
# 插入单条
result = collection.insert({'':""}) # 会自动为数据产生_id标识,并返回
# 插入多条
result = collection.insert([{}, {}]) # 返回_id集合
print(result)
## python3.x推荐使用下列方式,返回的是InsertOneResult
insert_one({})
insert_many([{}, {}])
print(result.inserted_id)
print(result.inserted_ids)

insert_one()

1
2
3
4
5
~~~

#### insert_many()

~~~python

查询

find(), find_one()

1
2
3
4
5
6
7
8
9
10
11
from bson.objectid import ObjectId
# 得到一个结果
result = collection.find_one({"a":"b"}) # 没有返回None
result = collection.find_one({"_id":"ObjectId('1325645654')"})

# 得到生成器对象cursor,可以用下标获取
results = collection.find({"age":"20"}) # pymongo.cursor
for result in results:
print(result)

results = collection.find({"age":{'$gt':20}}) # 大于20的
随机查询
1
2
3
results = collection.aggregate([ {'$sample': {'size':2000}}]) # 生成生成器
for result in results:
pass
比较符

GyHdBV.png

用正则表达式
1
2
results = collection.find ({ 'name': {'$ regex':'^M.*'}} )
# 这里使用$regex来指定正则匹配,人M.*代表以 M 开头的正则表达式。
功能符
GybBrt.png

计数

count()

1
result = colletion.find().count()

排序

sort()

1
2
results = colletion.find().sort('name',pymongo.ASCENDING)
print([result['name'] for result in results])

这里我们调用pymongo.ASCENDING指定升序。如果要降序排列,可以传入pymongo.DESCENDING

偏移

skip()

1
2
3
4
results = collection.find().sort('name', pymongo.ASCENDING).skip(2)
print([result['name'] for resuLt in results])
运行结果如下:
['Kevin', 'Mark', 'Mike']

值得注意的是,在数据库数量非常庞大的时候,如千万、亿级别,最好不要使用大的偏移量来查询数据,因为这样很可能导致内存溢出。此时可以使用类似如下操作来查询

limit()

设置结果个数

1
2
3
4
results = collection.find().sort('name', pymongo.ASCENDING).skip(2).limit(2)
print([result['name'] for result in results])
运行结果如下:
['Kevin', 'Mark']

更新

update()

1
2
3
4
5
6
condition = {"d": 'c'}
dict = colletion.find_one(condition)
dict["a"] = "b"
1.collection.update(condition, dict) // 直接用现在的dict替换之前的dict

>>>{'ok': 1, 'nModified*: 1, 'n': 1, 'updatedExisting': True}
1
2

2.collection.update(condition, {'$set': dict}) // 只更新存在的字段,其它字段不会删除

update( ) 方 法 其 实 也 是 官 方 不 推 荐 使 用 的 方 法 。这 里 也 分 为 update_one()方法和updatejnany()方法,用法更加严格,它们的第二个参数需要使用$类型操作符作为字典的键名

update_one()

1
2
3
4
5
6
7
8
9
10
11
condition = {'name': 'Kevin'}
student = collection.find_one(condition)
student['age'] = 26
resuIt = collection.update_one(condition, {'$set': student})
print(result)
print(result.matched_count, result.modified_count)


调用了 update_one()方法,第二个参数不能再直接传入修改后的字典,而是需要使用{'$set':
student}这样的形式,其返回结果是UpdateResult类型。然后分别调用 matched_count和 modified_count
属性,可以获得匹配的数据条数和影响的数据条数。
1
2
3
4
5
6
condition = { 'age': {'$gt': 20}}
result = collection.update_one(condition, {'$inc': {'age': 1}})
print(result)
print(result.matched_count, resuLt.modified_count)

这里指定查询条件为年龄大于20 , 然后更新条件为{'$inc': {'age':1}},也就是年龄加1, 执行之后会将第一条符合条件的数据年龄加1

update_many()

1
2
3
4
5
6
7
8
9
10
11
如果调用update_many()方法,则会将所有符合条件的数据都更新,示例如下:

condition = {'age': {'$gt': 20}}
result = collection.update_many(condition, {'$inc': {'age': 1}})
print(result)
print(result.mmtched_count, result.modified_count)

这时匹配条数就不再为1 条了,运行结果如下:
<pymongo.results.UpdateResult object at OxlOc6384c8>
3 3
可以看到,这时所有匹配到的数据都会被更新。
1
collection.update_many({}, {'$set':{'score':40}})

其返回结果是UpdateResult类型。然后分别J调用 matched_count和 modified_count
属性,可以获得匹配的数据条数和影响的数据条数

删除

remove()

1
colletion.remove(condition)

delete_one()

1
collection.delete_one(condtion)

delete_many()

1
colletion.delete_one({'age':{'$lt': 25}})

它们的返回结果 都 是 DeleteResult类型,可以调用deleted_count属性获取删除的数据条数。

其他操作

另外, PyMongo 还提供了一些组合方法,女口find_one_and_delete()、 find_one_and_replace()和find_one_and_update(),它们是查找后删除、替换和更新操作,其用法与上述方法基本一致。另外,还可以对索引进行操作,相 关 方 法 有 create_index()、 create_indexes()和 drop_index()等。

总结

1
1.cursor可以用 [index]

钟表可以回到起点,但永远不会回到昨天。

本文标题:崔庆才python3爬虫-pymongo

文章作者:TTYONG

发布时间:2020年04月06日 - 12:04

最后更新:2022年03月09日 - 21:03

原始链接:http://tianyong.fun/%E5%B4%94%E5%BA%86%E6%89%8Dpython3%E7%88%AC%E8%99%AB-pymongo.html

许可协议: 转载请保留原文链接及作者。

多少都是爱
0%