MongoDB是一个基于分布式文件存储的开源数据库系统,其内容存储形式类似JSON对象,它的字段值可以包含其他文档、数组及文档数组,非常灵活。
1.准备工作
安装好MongoDB并启动了其服务,安装好了PyMongo库。
2.连接MongoDB
我们在连接MongoDB时需要使用PyMongo库里面的MongoClient。一般来说,传入MongoDB的IP及端口即可。
import pymongo
client = pymongo.MongoClient(host='localhost', port=27017)
直接传入连接字符串也可以达到相同的效果。
client = pymongo.MongoClient('mongodb://localhost:27017/')
3.指定数据库
MongoDB中可以建立多个数据库,我们需要指定操作哪个数据库。我们指定一个test数据库。两种方法均可。
db = client.test
db = client['test']
4.指定集合
MongoDB的每个数据库里包含许多集合,他们类似与关系型数据库中的表。
下一步来指定需要操作的集合。我们指定一个students。同样有两种方式。
collection = db.students
collection = db['students']
这样就声明了一个Collection对象。
5.插入数据
对于students这个集合,新建一条学生数据,数据以字典类型表示:
student = {
'id': '20200101',
'name': 'mike',
'age': 18,
'gender': 'male'
}
result = collection.insert(student)
print(student)
5eb658e4b4a155c0bb3660f5
这里指定了学号,姓名,年龄和性别。然后调用collection的insert()方法即可插入数据。
在MongoDB中,每条数据其实只有一个_id属性来唯一标识。如果没有显式指明该属性,MongoDB会自动产生一个ObjectId类型的_id属性。insert()方法会在执行后返回_id值。
当然,我们也可以插入多条数据,以列表形式传递。
student1 = {
'id': '20200101',
'name': 'mike',
'age': 18,
'gender': 'male'
}
student2 = {
'id': '20200102',
'name': 'lily',
'age': '19',
'gender': 'female'
}
result = collection.insert([student1, student2])
print(result)
[ObjectId('5eb65af0222615a13187de7e'), ObjectId('5eb65af0222615a13187de7f')]
我们在使用python3时在运行时会Warning。
DeprecationWarning: insert is deprecated. Use insert_one or insert_many instead.
官方希望我们使用insert_one()和insert_many()方法来插入单条和多条数据,但是使用insert()方法也没什么问题。
6.查询
插入数据后,我们可以使用find_one()和find()方法来进行查询。find_one()得到的结果是单个结果,find()得到 的结果则是一个生成器对象。
result = collection.find_one({'name': 'mike'})
print(type(result))
print(result)
<class 'dict'>
{'_id': ObjectId('5eb658e4b4a155c0bb3660f5'), 'id': '20200101', 'name': 'mike', 'age': 18, 'gender': 'male'}
这里我们查询name为mike的数据,返回结果是字典类型。它多了一个_id属性,这是MongoDB在插入过程中自动添加的。
此外,我们也可以根据ObjectId来查询,此时需要使用bson库里的objectid:
result = collection.find_one({'_id': ObjectId('5eb658e4b4a155c0bb3660f5')})
print(result)
{'_id': ObjectId('5eb658e4b4a155c0bb3660f5'), 'id': '20200101', 'name': 'mike', 'age': 18, 'gender': 'male'}
另外还可以使用find()进行多条数据的查询。
results = collection.find({'age': 18})
print(results)
for result in results:
print(result)
返回结果是Cursor类型,它相当于一个生成器,我们需要遍历才能获取所有的结果。
如果要查询年龄大于18的数据可写为:
results = collection.find('age': {'$gt': 18}})
这里查询的条件键值已经不是单纯的数字了,而是一个字典,其键名为比较符号$gt,意思为大于。
$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]}}
另外,还可以使用正则匹配查询,例如查询以m开头的学生数据:
results = collection.find({'name': {'$regex': '^m.*'}})
还有其他的功能符号可在官方文档中查找。
7.计数
要统计查询结果有多少条数据,可以调用count()方法。
count = collection.find().count()
print(count)
或者统计符合某个条件的数据:
count = collection.find({'age': 18}).count()
print(count)
8.排序
排序时可以直接使用sort()方法,并在其中传入排序的字段及升降序标志即可。
results = collection.find().sort('name', pymongo.ASCENDING)
print([result['name'] for result in results])
pymongo.ASCENDING指定升序,pymongo.DESCENDING指定降序。
9.偏移
如果我们想只取某几个元素可以使用skip()方法偏移几个位置。如果偏移2个就是忽略前两个,从第3个开始。
results = collection.find().sort('name', pymongo.ASCENDING).skip(2)
还可以使用limit()方法来限制要取的个数。
results = collection.find().sort('name', pymongo.ASCENDING).skip(2).limit(2)
如果数据库量很大最好不要用大的偏移量来查询数据,因为这很可能导致内存溢出,可以使用之前的比较符号进行查询。
10.更新
对于数据更新,我们可以使用updata()方法,指定更新的条件和更新后的数据即可。
condition = {'name': 'mike'}
student = collection.find_one(condition)
student['age'] = 20
result = collection.update(condition, student)
print(result)
{'n': 1, 'nModified': 1, 'ok': 1, 'updatedExisting': True}
我们更新mike的年龄,首先指定查询条件,然后将数据查询出来,修改年龄,然后调用update()方法将原条件和修改后的数据传入。返回结果为字典形式,ok表示执行成功,nModified表示影响的数据条数。
我们还可以使用$set操作符来对数据进行更新。
result = collection.update(condition, {'$set': student})
这样就只会更新student字典里的片段。如果原先还有其他字段,则不会更新,也不会被删除。而如果不使用$set的话,则会把之前的数据全部用student字典替换;如果原来存在其他字符,则会被删除。
另外,update()方法和find()方法一样是官方不推荐使用的方法,有更严格的方法update_one()和update_many(),它们的第二个参数需要使用$类型操作符作为字典的键名。
condition = {'name': 'mike'}
student = collection.find_one(condition)
student['age'] = 20
result = collection.update_one(condition, {'$set': student})
print(result)
print(result.matched_count, result.modified_count)
<pymongo.results.UpdateResult object at 0x00000213D8EDC080>
1 0
返回结果是UpdateResult类型。然后分别调用matched_count和modified_count属性来返回匹配的数据条数和影响的数据条数。
condition = {'age': {'$gt': 18}}
result = collection.update_one(condition, {'$inc': {'age': 1}})
print(result)
print(result.matched_count, result.modified_count)
<pymongo.results.UpdateResult object at 0x0000025C1DEDC200>
1 1
我们指定查询年龄大于18,更新条件为{'$inc': {'age: 1}}),也就是年龄加1,执行后会将第一条符合条件的数据年龄加1。
但如果调用update_many()方法,则所有符合条件的数据都会更新。
condition = {'age': {'$gt': 18}}
result = collection.update_many(condition, {'$inc': {'age': 1}})
print(result)
print(result.matched_count, result.modified_count)
<pymongo.results.UpdateResult object at 0x0000025C1DEDC200>
2 2
11.删除
直接调用remove()方法即可。
result = collection.remove({'name': 'mike'})
print(result)
{'ok': 1,'n': 1}
同时删除也有另两种方法——delete_one()和delete_many()
result = collection.delete_one({'name': 'mike'})
result = collection.delete_many({'age': {'$lt': 20}})
delete_one()即删除第一条符合条件的数据,delete_many()则是删除所有符合条件的数据,还可以使用delete_count属性来获取删除的条数。
关于MongoDB的其他操作可参考官方文档。