在开始以前,请确保已经安装好了MongoDB并启动了其服务,而且安装好了Python的PyMongo库。html
链接MongoDB时,咱们须要使用PyMongo库里面的MongoClient
。通常来讲,传入MongoDB的IP及端口便可,其中第一个参数为地址host
,第二个参数为端口port
(若是不给它传递参数,默认是27017):python
import pymongo client = pymongo.MongoClient(host='localhost', port=27017)
这样就能够建立MongoDB的链接对象了。正则表达式
另外,MongoClient
的第一个参数host
还能够直接传入MongoDB的链接字符串,它以mongodb
开头,例如:mongodb
client = MongoClient('mongodb://localhost:27017/')
这也能够达到一样的链接效果。数据库
MongoDB中能够创建多个数据库,接下来咱们须要指定操做哪一个数据库。这里咱们以test数据库为例来讲明,下一步须要在程序中指定要使用的数据库:api
db = client.test
这里调用client
的test
属性便可返回test数据库。固然,咱们也能够这样指定:post
db = client['test']
这两种方式是等价的。3d
MongoDB的每一个数据库又包含许多集合(collection),它们相似于关系型数据库中的表。code
下一步须要指定要操做的集合,这里指定一个集合名称为students。与指定数据库相似,指定集合也有两种方式:htm
collection = db.students collection = db['students']
这样咱们便声明了一个Collection
对象。
接下来,即可以插入数据了。对于students这个集合,新建一条学生数据,这条数据以字典形式表示:
student = { 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male' }
这里指定了学生的学号、姓名、年龄和性别。接下来,直接调用collection
的insert()
方法便可插入数据,代码以下:
result = collection.insert(student) print(result)
在MongoDB中,每条数据其实都有一个_id
属性来惟一标识。若是没有显式指明该属性,MongoDB会自动产生一个ObjectId
类型的_id
属性。insert()
方法会在执行后返回_id
值。
运行结果以下:
5932a68615c2606814c91f3d
固然,咱们也能够同时插入多条数据,只须要以列表形式传递便可,示例以下:
student1 = { 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male' } student2 = { 'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male' } result = collection.insert([student1, student2]) print(result)
返回结果是对应的_id
的集合:
[ObjectId('5932a80115c2606a59e8a048'), ObjectId('5932a80115c2606a59e8a049')]
实际上,在PyMongo 3.x版本中,官方已经不推荐使用insert()
方法了。固然,继续使用也没有什么问题。官方推荐使用insert_one()
和insert_many()
方法来分别插入单条记录和多条记录,示例以下:
student = { 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male' } result = collection.insert_one(student) print(result) print(result.inserted_id)
运行结果以下:
<pymongo.results.InsertOneResult object at 0x10d68b558> 5932ab0f15c2606f0c1cf6c5
与insert()
方法不一样,此次返回的是InsertOneResult
对象,咱们能够调用其inserted_id
属性获取_id
。
对于insert_many()
方法,咱们能够将数据以列表形式传递,示例以下:
student1 = { 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male' } student2 = { 'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male' } result = collection.insert_many([student1, student2]) print(result) print(result.inserted_ids)
运行结果以下:
<pymongo.results.InsertManyResult object at 0x101dea558> [ObjectId('5932abf415c2607083d3b2ac'), ObjectId('5932abf415c2607083d3b2ad')]
该方法返回的类型是InsertManyResult
,调用inserted_ids
属性能够获取插入数据的_id
列表。
插入数据后,咱们能够利用find_one()
或find()
方法进行查询,其中find_one()
查询获得的是单个结果,find()
则返回一个生成器对象。示例以下:
result = collection.find_one({'name': 'Mike'}) print(type(result)) print(result)
这里咱们查询name
为Mike
的数据,它的返回结果是字典类型,运行结果以下:
<class 'dict'> {'_id': ObjectId('5932a80115c2606a59e8a049'), 'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male'}
能够发现,它多了_id
属性,这就是MongoDB在插入过程当中自动添加的。
此外,咱们也能够根据ObjectId
来查询,此时须要使用bson库里面的objectid
:
from bson.objectid import ObjectId result = collection.find_one({'_id': ObjectId('593278c115c2602667ec6bae')}) print(result)
其查询结果依然是字典类型,具体以下:
{'_id': ObjectId('593278c115c2602667ec6bae'), 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male'}
固然,若是查询结果不存在,则会返回None
。
对于多条数据的查询,咱们可使用find()
方法。例如,这里查找年龄为20的数据,示例以下:
results = collection.find({'age': 20}) print(results) for result in results: print(result)
运行结果以下:
<pymongo.cursor.Cursor object at 0x1032d5128> {'_id': ObjectId('593278c115c2602667ec6bae'), 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male'} {'_id': ObjectId('593278c815c2602678bb2b8d'), 'id': '20170102', 'name': 'Kevin', 'age': 20, 'gender': 'male'} {'_id': ObjectId('593278d815c260269d7645a8'), 'id': '20170103', 'name': 'Harden', 'age': 20, 'gender': 'male'}
返回结果是Cursor
类型,它至关于一个生成器,咱们须要遍历取到全部的结果,其中每一个结果都是字典类型。
若是要查询年龄大于20的数据,则写法以下:
results = collection.find({'age': {'$gt': 20}})
这里查询的条件键值已经不是单纯的数字了,而是一个字典,其键名为比较符号$gt
,意思是大于,键值为20。
这里将比较符号概括为下表。
符号 | 含义 | 示例 |
---|---|---|
$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.*'}})
这里使用$regex
来指定正则匹配,^M.*
表明以M开头的正则表达式。
这里将一些功能符号再归类为下表。
符号 | 含义 | 示例 | 示例含义 |
---|---|---|---|
$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': 'Mike'}} |
text 类型的属性中包含Mike 字符串 |
$where |
高级条件查询 | {'$where': 'obj.fans_count == obj.follows_count'} |
自身粉丝数等于关注数 |
关于这些操做的更详细用法,能够在MongoDB官方文档找到:
https://docs.mongodb.com/manual/reference/operator/query/。
要统计查询结果有多少条数据,能够调用count()
方法。好比,统计全部数据条数:
count = collection.find().count() print(count)
或者统计符合某个条件的数据:
count = collection.find({'age': 20}).count() print(count)
运行结果是一个数值,即符合条件的数据条数。
排序时,直接调用sort()
方法,并在其中传入排序的字段及升降序标志便可。示例以下:
results = collection.find().sort('name', pymongo.ASCENDING) print([result['name'] for result in results])
运行结果以下:
['Harden', 'Jordan', 'Kevin', 'Mark', 'Mike']
这里咱们调用pymongo.ASCENDING
指定升序。若是要降序排列,能够传入pymongo.DESCENDING
。
在某些状况下,咱们可能想只取某几个元素,这时能够利用skip()
方法偏移几个位置,好比偏移2,就忽略前两个元素,获得第三个及之后的元素:
results = collection.find().sort('name', pymongo.ASCENDING).skip(2) print([result['name'] for result in results])
运行结果以下:
['Kevin', 'Mark', 'Mike']
另外,还能够用limit()
方法指定要取的结果个数,示例以下:
results = collection.find().sort('name', pymongo.ASCENDING).skip(2).limit(2) print([result['name'] for result in results])
运行结果以下:
['Kevin', 'Mark']
若是不使用limit()
方法,本来会返回三个结果,加了限制后,会截取两个结果返回。
值得注意的是,在数据库数量很是庞大的时候,如千万、亿级别,最好不要使用大的偏移量来查询数据,由于这样极可能致使内存溢出。此时可使用相似以下操做来查询:
from bson.objectid import ObjectId collection.find({'_id': {'$gt': ObjectId('593278c815c2602678bb2b8d')}})
这时须要记录好上次查询的_id
。
对于数据更新,咱们可使用update()
方法,指定更新的条件和更新后的数据便可。例如:
condition = {'name': 'Kevin'} student = collection.find_one(condition) student['age'] = 25 result = collection.update(condition, student) print(result)
这里咱们要更新name
为Kevin
的数据的年龄:首先指定查询条件,而后将数据查询出来,修改年龄后调用update()
方法将原条件和修改后的数据传入。
运行结果以下:
{'ok': 1, 'nModified': 1, 'n': 1, 'updatedExisting': True}
返回结果是字典形式,ok
表明执行成功,nModified
表明影响的数据条数。
另外,咱们也可使用$set
操做符对数据进行更新,代码以下:
result = collection.update(condition, {'$set': student})
这样能够只更新student
字典内存在的字段。若是原先还有其余字段,则不会更新,也不会删除。而若是不用$set
的话,则会把以前的数据所有用student
字典替换;若是本来存在其余字段,则会被删除。
另外,update()
方法其实也是官方不推荐使用的方法。这里也分为update_one()
方法和update_many()
方法,用法更加严格,它们的第二个参数须要使用$
类型操做符做为字典的键名,示例以下:
condition = {'name': 'Kevin'} student = collection.find_one(condition) student['age'] = 26 result = collection.update_one(condition, {'$set': student}) print(result) print(result.matched_count, result.modified_count)
这里调用了update_one()
方法,第二个参数不能再直接传入修改后的字典,而是须要使用{'$set': student}
这样的形式,其返回结果是UpdateResult
类型。而后分别调用matched_count
和modified_count
属性,能够得到匹配的数据条数和影响的数据条数。
运行结果以下:
<pymongo.results.UpdateResult object at 0x10d17b678> 1 0
咱们再看一个例子:
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。
运行结果以下:
<pymongo.results.UpdateResult object at 0x10b8874c8> 1 1
能够看到匹配条数为1条,影响条数也为1条。
若是调用update_many()
方法,则会将全部符合条件的数据都更新,示例以下:
condition = {'age': {'$gt': 20}} result = collection.update_many(condition, {'$inc': {'age': 1}}) print(result) print(result.matched_count, result.modified_count)
这时匹配条数就再也不为1条了,运行结果以下:
<pymongo.results.UpdateResult object at 0x10c6384c8> 3 3
能够看到,这时全部匹配到的数据都会被更新。
删除操做比较简单,直接调用remove()
方法指定删除的条件便可,此时符合条件的全部数据均会被删除。示例以下:
result = collection.remove({'name': 'Kevin'}) print(result)
运行结果以下:
{'ok': 1, 'n': 1}
另外,这里依然存在两个新的推荐方法——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)
运行结果以下:
<pymongo.results.DeleteResult object at 0x10e6ba4c8> 1 4
delete_one()
即删除第一条符合条件的数据,delete_many()
即删除全部符合条件的数据。它们的返回结果都是DeleteResult
类型,能够调用deleted_count
属性获取删除的数据条数。
另外,PyMongo还提供了一些组合方法,如find_one_and_delete()
、find_one_and_replace()
和find_one_and_update()
,它们是查找后删除、替换和更新操做,其用法与上述方法基本一致。
另外,还能够对索引进行操做,相关方法有create_index()
、create_indexes()
和drop_index()
等。
关于PyMongo的详细用法,能够参见官方文档:http://api.mongodb.com/python/current/api/pymongo/collection.html。
另外,还有对数据库和集合自己等的一些操做,这里再也不一一讲解,能够参见官方文档:http://api.mongodb.com/python/current/api/pymongo/。