1.链接MongoDBhtml
链接 MongoDB 咱们须要使用 PyMongo 库里面的 MongoClient,通常来讲传入 MongoDB 的 IP 及端口便可,第一个参数为地址 host,第二个参数为端口 port,端口若是不传默认是 27017。python
import pymongo client = pymongo.MongoClient(host='localhost', port=27017) # client = MongoClient('mongodb://localhost:27017/')
2.指定数据库正则表达式
import pymongo client = pymongo.MongoClient(host='localhost', port=27017) # client = MongoClient('mongodb://localhost:27017/') db = client.test # db = client['test']
3.指定集合mongodb
MongoDB 的每一个数据库又包含了许多集合 Collection,也就相似与关系型数据库中的表数据库
import pymongo client = pymongo.MongoClient(host='localhost', port=27017) # client = MongoClient('mongodb://localhost:27017/') db = client.test # db = client['test'] collection = db.students # collection = db['students']
4.插入数据api
在 MongoDB 中,每条数据其实都有一个 _id 属性来惟一标识,若是没有显式指明 _id,MongoDB 会自动产生一个 ObjectId 类型的 _id 属性。insert() 方法会在执行后返回的 _id 值。也能够在插入的时候指定_id的值。spa
也能够同时插入多条数据,只须要以列表形式传递便可,返回的结果是对应的 _id 的集合。3d
import pymongo client = pymongo.MongoClient(host='localhost', port=27017) # client = MongoClient('mongodb://localhost:27017/') db = client.test # db = client['test'] collection = db.students # collection = db['students'] # 插入单条数据 student = { 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male' } result = collection.insert_one(student) print(result) print(result.inserted_id) # 返回的是InsertOneResult 对象,咱们能够调用其 inserted_id 属性获取 _id """ 运行结果: <pymongo.results.InsertOneResult object at 0x10d68b558> 5932ab0f15c2606f0c1cf6c5 """ # 插入多条数据 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) # insert_many() 方法返回的类型是 InsertManyResult,调用inserted_ids 属性能够获取插入数据的 _id 列表 """ 运行结果: <pymongo.results.InsertManyResult object at 0x101dea558> [ObjectId('5932abf415c2607083d3b2ac'), ObjectId('5932abf415c2607083d3b2ad')] """
5.查询数据code
能够利用 find_one() 或 find() 方法进行查询,find_one() 查询获得是单个结果,find() 则返回一个生成器对象。htm
import pymongo client = pymongo.MongoClient(host='localhost', port=27017) # client = MongoClient('mongodb://localhost:27017/') db = client.test # db = client['test'] collection = db.students # collection = db['students'] result = collection.find_one({'name': 'Mike'}) print(type(result)) # 查询 name 为 Mike 的数据,它的返回结果是字典类型 print(result) # 多了一个 _id 属性,这就是 MongoDB 在插入的过程当中自动添加的 """ <class 'dict'> {'_id': ObjectId('5c502697e0b72c0d90eeee22'), 'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male'} """ # 也能够直接根据 ObjectId 来查询,这里须要使用 bson 库里面的 ObjectId """ from bson.objectid import ObjectId result = collection.find_one({'_id': ObjectId('593278c115c2602667ec6bae')}) print(result) """ # 多条数据的查询,使用 find() 方法 results = collection.find({'age': 20}) print(results) for result in results: print(result) # 返回结果是 Cursor 类型,至关于一个生成器,咱们须要遍历取到全部的结果,每个结果都是字典类型 # 要查询年龄大于 20 的数据 results = collection.find({'age': {'$gt': 20}}) # 查询的条件键值是一个字典,其键名为比较符号 $gt,意思是大于,键值为 20
符号 |
含义 |
示例 |
$lt |
小于 |
|
$gt |
大于 |
|
$lte |
小于等于 |
|
$gte |
大于等于 |
|
$ne |
不等于 |
|
$in |
在范围内 |
|
$nin |
不在范围内 |
|
# 还能够进行正则匹配查询,例如查询名字以 M 开头的学生数据 results = collection.find({'name': {'$regex': '^M.*'}}) # 使用了 $regex 来指定正则匹配,^M.* 表明以 M 开头的正则表达式s
符号 |
含义 |
示例 |
示例含义 |
$regex |
匹配正则 |
|
name 以 M开头 |
$exists |
属性是否存在 |
|
name 属性存在 |
$type |
类型判断 |
|
age 的类型为 int |
$mod |
数字模操做 |
|
年龄模 5 余 0 |
$text |
文本查询 |
|
text 类型的属性中包含 Mike 字符串 |
$where |
高级条件查询 |
|
自身粉丝数等于关注数 |
6.统计/计数
import pymongo client = pymongo.MongoClient(host='localhost', port=27017) # client = MongoClient('mongodb://localhost:27017/') db = client.test # db = client['test'] collection = db.students count = collection.find().count() # 统计全部数据条数 print(count) count = collection.find({'age': 20}).count() # 统计符合某个条件的数据 print(count)
7.排序
import pymongo client = pymongo.MongoClient(host='localhost', port=27017) # client = MongoClient('mongodb://localhost:27017/') db = client.test # db = client['test'] collection = db.students results = collection.find().sort('name', pymongo.ASCENDING) # pymongo.ASCENDING 指定升序,降序排列能够传入 pymongo.DESCENDING print([result['name'] for result in results])
8.偏移
注意:在数据库数量很是庞大的时候,如千万、亿级别,最好不要使用大的偏移量来查询数据,极可能会致使内存溢出,使用步骤5进行查询
import pymongo client = pymongo.MongoClient(host='localhost', port=27017) # client = MongoClient('mongodb://localhost:27017/') db = client.test # db = client['test'] collection = db.students # 在某些状况下咱们可能想只取某几个元素,在这里能够利用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])
9.更新
import pymongo client = pymongo.MongoClient(host='localhost', port=27017) # client = MongoClient('mongodb://localhost:27017/') db = client.test # db = client['test'] collection = db.students # update_one和update_many,第一个参数是条件,第二个参数须要使用 $ 类型操做符做为字典的键名 condition = {'name': 'Mike'} student = collection.find_one(condition) student['age'] = 26 result = collection.update_one(condition, {'$set': student}) # 返回结果是 UpdateResult 类型,调用 matched_count 和 modified_count 属性分别能够得到匹配的数据条数和影响的数据条数 print(result) print(result.matched_count, result.modified_count) # 指定查询条件为年龄大于 20,而后更新条件为 {'$inc': {'age': 1}},也就是年龄加 1,执行以后会将第一条符合条件的数据年龄加 1 condition = {'age': {'$gt': 20}} result = collection.update_one(condition, {'$inc': {'age': 1}}) print(result) print(result.matched_count, result.modified_count) # 调用 update_many() 方法,则会将全部符合条件的数据都更新 condition = {'age': {'$gt': 20}} result = collection.update_many(condition, {'$inc': {'age': 1}}) print(result) print(result.matched_count, result.modified_count)
10.删除
import pymongo client = pymongo.MongoClient(host='localhost', port=27017) # client = MongoClient('mongodb://localhost:27017/') db = client.test # db = client['test'] collection = db.students # delete_one() 即删除第一条符合条件的数据,delete_many() 即删除全部符合条件的数据 # 返回结果是 DeleteResult 类型,能够调用 deleted_count 属性获取删除的数据条数 result = collection.delete_one({'name': 'Mike'}) print(result) print(result.deleted_count) result = collection.delete_many({'age': {'$lt': 25}}) print(result.deleted_count)
11.组合方法
find_one_and_delete() 查找后删除
find_one_and_replace() 查找后替换
find_one_and_update() 查找后更新
还能够对索引进行操做,如 create_index()、create_indexes()、drop_index() 等。
详细用法能够参见官方文档:http://api.mongodb.com/python/current/api/pymongo/collection.html
还有对数据库、集合自己以及其余的一些操做,能够参见官方文档:http://api.mongodb.com/python/current/api/pymongo/