前言
- 最近做毕设用到pymongo,对平常的使用记录一下。
pymongo
配置环境
python3.6
,pymongo
,MongoDB数据库
- 数据库配置:
- uri:
localhost:27017
- db:
douban
- collection:
human
- uri:
连接MongoDB
- 连接MongoDB我们需要使用PyMongo库里面的MongoClient,一般来说传入MongoDB的IP及端口即可,第一个参数为地址host,第二个参数为端口port,端口默认是27017。
代码:
1
2
3
4import pymongo
client = pymongo.MongoClient(host='localhost', port=27017)
# 或者如下
client = pymongo.MongoClient('mongodb://localhost:27017')指定数据库
1
2
3db = client.douban
db = client['douban']
# 上面两种方式是等价的指定集合
1
2
3collection = db.peoples
collection = db['peoples']
# 上面两种方式是等价的
插入数据(以字典的形式表示)
1
2
3
4
5
6
7
8
9
10在PyMongo 3.X版本中,insert()方法官方已经不推荐使用
people = {
'name': 'roux',
'age': 20,
'sex': 'male'
}
result = collection.insert(people)
print(result)
# 在MongoDB中,每条数据其实都有一个_id属性来唯一标识,如果没有显式指明_id,MongoDB会自动产生一个ObjectId类型的_id属性
# insert()方法会在执行后返回的_id值1
2
3
4
5
6
7
8
9
10
11
12
13
14
15# 同时插入多条数据,只需要以列表形式传递即可,示例如下:
people1 = {
'name': 'roux',
'age': 20,
'sex': 'male'
}
people2 = {
'name': 'shirsen',
'age': 21,
'sex': 'female'
}
result = collection.insert([people1, people2])
print(result)
# 返回的结果是对应的_id的集合1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31# 官方推荐使用insert_one()和insert_many()方法将插入单条和多条记录分开。
people = {
'name': 'roux',
'age': 20,
'sex': 'male'
}
result = collection.insert_one(people)
print(result)
print(result.inserted_id)
# 返回结果和insert()方法不同,这次返回的是InsertOneResult对象,我们可以调用其inserted_id属性获取_id。
# 对于insert_many()方法,我们可以将数据以列表形式传递即可,示例如下:
people1 = {
'name': 'roux',
'age': 20,
'sex': 'male'
}
people2 = {
'name': 'shirsen',
'age': 21,
'sex': 'male'
}
result = collection.insert_many([people1, people2])
print(result)
print(result.inserted_ids)
# insert_many()方法返回的类型是InsertManyResult,调用inserted_ids属性可以获取插入数据的_id列表查询
1
2
3
4
5result = collection.find_one({'name': 'shirsen'})
print(type(result))
print(result)
# 在这里我们查询name为shirsen的数据,它的返回结果是字典类型
# 可以发现它多了一个_id属性,这就是MongoDB在插入的过程中自动添加的。1
2
3
4
5
6
7
8# 我们也可以直接根据ObjectId来查询,这里需要使用bson库里面的ObjectId。
from bson.objectid import ObjectId
result = collection.find_one({'_id': ObjectId('593278c115c2602667ec6bae')})
print(result)
# 其查询结果依然是字典类型
# 如果查询_id':结果不存在则会返回None。1
2
3
4
5
6
7
8
9
10
11
12# 对于多条数据的查询,我们可以使用find()方法,例如在这里查找年龄为20的数据
results = collection.find({'age': 20})
print(results)
for result in results:
print(result)
# 返回结果是Cursor类型,相当于一个生成器,我们需要遍历取到所有的结果,每一个结果都是字典类型。
# 如果要查询年龄大于20的数据,则写法如下:
results = collection.find({'age': {'$gt': 20}})
# 在这里查询的条件键值已经不是单纯的数字了,而是一个字典,其键名为比较符号$gt,意思是大于,键值为20,这样便可以查询出所有年龄大于20的数据。1
2
3
4
5
6
7
8
9
10# 比较符号归纳如下表:
符号含义示例
$lt 小于: {'age': {'$lt': 20}}
$gt 大于: {'age': {'$gt': 20}}
$lte 小于等于: {'age': {'$lte': 20}}
$gte 大于等于: {'age': {'$gte': 20}}
$ne 不等于: {'age': {'$ne': 20}}
$in 在范围内: {'age': {'$in': [20, 23]}}
$nin 不在范围内: {'age': {'$nin': [20, 23]}}1
2
3
4# 另外还可以进行正则匹配查询,例如查询名字以M开头的学生数据,示例如下:
results = collection.find({'name': {'$regex': '^M.*'}})
# 在这里使用了$regex来指定正则匹配,^M.*代表以M开头的正则表达式,这样就可以查询所有符合该正则的结果。1
2
3
4
5
6
7
8
9# 功能符号归类如下:
符号含义示例示例含义
$regex 匹配正则: {'name': {'$regex': '^M.*'}}, name以M开头
$exists 属性是否存在: {'name': {'$exists': True}}, name属性存在
$type 类型判断: {'age': {'$type': 'int'}}, age的类型为int
$mod 数字模操作: {'age': {'$mod': [5, 0]}}, 年龄模5余0
$text 文本查询: {'$text': {'$search': 'shirsen'}}, text类型的属性中包含shirsen字符串
$where 高级条件查询: {'$where': 'obj.fans_count == obj.follows_count'}, 自身粉丝数等于关注数计数
1
2
3
4
5
6
7# 要统计查询结果有多少条数据,可以调用count()方法,如统计所有数据条数:
count = collection.find().count()
print(count)
# 或者统计符合某个条件的数据:
count = collection.find({'age': 20}).count()
print(count)排序
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15# 可以调用sort方法,传入排序的字段及升降序标志即可
results = collection.find().sort('name', pymongo.ASCENDING)
print([result['name'] for result in results])
# 偏移,可能想只取某几个元素,在这里可以利用skip()方法偏移几个位置,比如偏移2,就忽略前2个元素,得到第三个及以后的元素。
results = collection.find().sort('name', pymongo.ASCENDING).skip(2)
print([result['name'] for result in results])
# 另外还可以用limit()方法指定要取的结果个数
results = collection.find().sort('name', pymongo.ASCENDING).skip(2).limit(2)
print([result['name'] for result in results])
# 如果不加limit()原本会返回三个结果,加了限制之后,会截取2个结果返回。
# 值得注意的是,在数据库数量非常庞大的时候,如千万、亿级别,最好不要使用大的偏移量来查询数据,很可能会导致内存溢出,
# 可以使用类似find({'_id': {'$gt': ObjectId('593278c815c2602678bb2b8d')}}) 这样的方法来查询,记录好上次查询的_id。更新
1
2
3
4
5
6
7
8
9
10
11
12# 对于数据更新可以使用update()方法,指定更新的条件和更新后的数据即可,例如:
condition = {'name': 'Kevin'}
people = collection.find_one(condition)
people['age'] = 25
result = collection.update(condition, people)
print(result)
# 在这里我们将name为Kevin的数据的年龄进行更新,首先指定查询条件,然后将数据查询出来,修改年龄,
# 之后调用update方法将原条件和修改后的数据传入,即可完成数据的更新。
# 返回结果是字典形式,ok即代表执行成功,nModified代表影响的数据条数。
# 另外update()方法其实也是官方不推荐使用的方法1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20# 在这里也分了update_one()方法和update_many()方法,用法更加严,第二个参数需要使用$类型操作符作为字典的键名,我们用示例感受一下。
condition = {'name': 'Kevin'}
people = collection.find_one(condition)
people['age'] = 26
result = collection.update_one(condition, {'$set': people})
print(result)
print(result.matched_count, result.modified_count)
# 在这里调用了update_one方法,第二个参数不能再直接传入修改后的字典,而是需要使用{'$set': people}这样的形式,
# 其返回结果是UpdateResult类型,然后调用matched_count和modified_count属性分别可以获得匹配的数据条数和影响的数据条数。
# 再看一个例子:
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
2
3
4
5
6
7
8
9
10# 如果调用update_many()方法,则会将所有符合条件的数据都更新
condition = {'age': {'$gt': 20}}
result = collection.update_many(
condition,
{'$inc': {'age': 1}}
)
print(result)
print(result.matched_count, result.modified_count)
# 这时所有匹配到的数据都会被更新。删除
1
2
3
4
5
6
7
8
9
10
11
12
13# 删除操作比较简单,直接调用remove()方法指定删除的条件即可,符合条件的所有数据均会被删除
result = collection.remove({'name': 'Kevin'})
print(result)
# 另外依然存在两个新的推荐方法,delete_one()和delete_many()方法
result = collection.delete_one({'name': 'Kevin'})
print(result)
print(result.deleted_count)
result = collection.delete_many({'age': {'$lt': 25}})
print(result.deleted_count)
# delete_one()即删除第一条符合条件的数据,delete_many()即删除所有符合条件的数据,返回结果是DeleteResult类型,
# 可以调用deleted_count属性获取删除的数据条数。更多
1
2
3# 另外PyMongo还提供了一些组合方法,如find_one_and_delete()、find_one_and_replace()、find_one_and_update(),查找后删除、替换、更新操作,用法与上述方法基本一致。
# 另外还可以对索引进行操作,如create_index()、create_indexes()、drop_index()等。
特殊查询
忽略大小写
可以使用正则查询
1
2
3
4
5
6
7
8
9
10
11import re
import pymongo
name = r"^{}s$".format(filename)
name = re.complie(name, re.I)
client = pymongo.MongoClient(host, port)
db = client['database']
col = db['collection']
result = col.find({'filename': name}, project={'_id': False})
# 或者使用 $regex 表达式
result = col.find({'filename': {'$regex': r"^{}s$".format(filename), '$options': 'i'}}, project={'_id': False})$options 支持如下:
选型 | 含义 | 要求 |
---|---|---|
i | 大小写不敏感 | |
m | 查询中使用了锚,如^ 或者$ ,以及匹配\n 后的字符串 |
|
x | 忽视所有空白字符 | 要求$regex 与$option 合用 |
s | 允许点字符 . 匹配所有的字符,包括换行符 |
要求$regex 与$option 合用 |
是否含有
代码:
1
2
3
4
5# 查找存在name属性的数据
col.find_one({'name': {'$exists': True}})
# 查找name为None的数据
col.find({'name': {'$exists': True, '$in': [None]}})
多层结构查询
代码:
1
2# info 里面嵌套 name
col.find_one({'info.name': 'roux'})
逻辑查询
代码:
1
2
3
4
5
6
7
8# and 查询
col.find_one({'name': 'roux', 'id': 1})
# or 查询
col.find({"$or": [{'name': 'roux'}, {'id': 1}]})
# in 查询
col.find({'name': {"$in": ['roux', 'shirsen']}})