08 pymongo

pymongo

安装

pip install pymongo

链接MongoDB

import pymongo


# 链接MongoDB
client = pymongo.MongoClient(host='localhost', port=27017)
# client = pymongo.MongoClient('mongodb://localhost:27017/')  # 此方式也能够


# 指定数据库
db = client.test
# db = client['test']  # 此方式也能够


# 指定集合
collection = db.students
# collection = db['students']  # 此方式也能够

集合操做

    官方文档html

添加

1 insertpython

    在MongoDB中,每条数据其实都有一个_id属性来惟一标识,若是没有显式指明_id,MongoDB会自动产生一个ObjectId类型的_id属性。mongodb

    insert()方法执行后返回_id值数据库

student = {
    'id': '20170101',
    'name': 'ethan1',
    'age': 20,
    'gender': 'male'
}
result = collection.insert(student)
print(result)  # 5c806e95ebdaee2a304fbf78

student1 = {
    'id': '20170101',
    'name': 'ethan2',
    'age': 20,
    'gender': 'male'
}

student2 = {
    'id': '20170202',
    'name': 'ethan3',
    'age': 21,
    'gender': 'male'
}

result = collection.insert([student1, student2])
print(result)  # [ObjectId('5c806f69ebdaee2ac019041f'), ObjectId('5c806f69ebdaee2ac0190420')]

2 insert_one&insert_manyapi

    在pymongo 3.X版本中,insert()方法官方已经不推荐使用了,固然继续使用也没有什么问题。spa

    官方推荐使用insert_one()和insert_many()方法将插入单条和多条记录分开。code

    insert_one()返回结果与insert()不一样,这次返回的是InsertOneResult对象,调用其inserted_id属性获取_id,inert_many()返回的是InsertManyResult对象,调用inserted_ids属性获取_id列表。htm

# insert_one
student = {
    'id': '20170101',
    'name': 'ethan4',
    'age': 20,
    'gender': 'male'
}

result = collection.insert_one(student)
print(result)  # <pymongo.results.InsertOneResult object at 0x000001C4A65A9C48>
print(result.inserted_id)  # 5c8071f5ebdaee2e205a6129


# insert_many
student1 = {
    'id': '20170101',
    'name': 'ethan5',
    'age': 20,
    'gender': 'male'
}

student2 = {
    'id': '20170202',
    'name': 'ethan6',
    'age': 21,
    'gender': 'male'
}

result = collection.insert_many([student1, student2])
print(result)  # <pymongo.results.InsertManyResult object at 0x0000026F6865ACC8>
print(result.inserted_ids)  # [ObjectId('5c807236ebdaee2568d6fabc'), ObjectId('5c807236ebdaee2568d6fabd')]

查询

    官方文档对象

1 find_oneblog

    find_one()查询获得的是单个结果,返回类型为字典类型。

    也可根据ObjectId来查询,查询结果依然是字典类型。若是查询_id不存在则返回None

result = collection.find_one({'name': 'ethan4'})
print(type(result))  # <class 'dict'>
print(result)  # {'_id': ObjectId('5c8071f5ebdaee2e205a6129'), 'id': '20170101', 'name': 'ethan4', 'age': 20, 'gender': 'male'}

from bson.objectid import ObjectId

result = collection.find_one({'_id': ObjectId('5c8071f5ebdaee2e205a6129')})
print(result)  # {'_id': ObjectId('5c8071f5ebdaee2e205a6129'), 'id': '20170101', 'name': 'ethan4', 'age': 20, 'gender': 'male'}

2 find

    查询多条数据,返回多个结果。返回结果为Cursor类型,至关于一个生成器,须要遍历取到全部结果,每个结果都是字典类型。

查询年龄为20的数据
results = collection.find({'age': 20})
print(results)  # <pymongo.cursor.Cursor object at 0x000002511CFA3860>  至关于生成器
for result in results:
    print(result)

查询年龄大于20的数据
results = collection.find({"age": {"$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]}}
"""

正则匹配查询
results = collection.find({"name": {"regex": '^e.*'}})

"""
符号含义示例示例含义
$regex匹配正则{'name': {'$regex': '^e.*'}}name以M开头
$exists属性是否存在{'name': {'$exists': True}}name属性存在
$type类型判断{'age': {'$type': 'int'}}age的类型为int
$mod数字模操做{'age': {'$mod': [5, 0]}}年龄模5余0
$text文本查询{'$text': {'$search': 'ethan'}}text类型的属性中包含ethan字符串
$where高级条件查询{'$where': 'obj.fans_count == obj.follows_count'}自身粉丝数等于关注数
"""

计数
count = collection.find().count()
count = collection.find({"age": 20}).count()


排序
results = collection.find().sort("name", pymongo.ASCENDING)

# 偏移, 例偏移2,就忽略前2个元素,获得第三个及之后的元素
results = collection.find().sort("name", pymongo.ASCENDING).skip(2)

# limit 指定要取的结果个数
results = collection.find().sort("name", pymongo.ASCENDING).skip(2).limit(2)

    值得注意的是,在数据库数量很是宠大的时候,如千万、亿级别,最好不要使用大的偏移量来查询数据,极可能会致使内存溢出。可使用相似find({'_id': {'$gt': ObjectId('593278c815c2602678bb2b8d')}}) 这样的方法来查询,记录好上次查询的_id。

更新

1 update

    返回结果为字典形式,ok即代码执行成功,nModified表明影响的数据条数

condition = {'name': 'ethan5'}
student = collection.find_one(condition)
student['age'] = 25
result = collection.update(condition, student)
print(result)  #{'n': 1, 'nModified': 1, 'ok': 1.0, 'updatedExisting': True}

2 update_one

    update()方法其实也是官网不推荐使用的方法。官方推荐使用update_one()和update_many()。用法更严格,第二个参数须要使用$类型操做符做为字典的键名。

    其返回结果是UpdateResult类型,而后调用matched_count和modified_count属性分别得到匹配的数据条数和影响的数据条数

condition = {'name': 'ethan5'}
student = collection.find_one(condition)
student['age'] = 26
result = collection.update_one(condition, {"$set": student})
print(result)  # <pymongo.results.UpdateResult object at 0x0000029E51C4BBC8>
print(result.matched_count, result.modified_count)  # 1 0

# 指定查询条件为年龄大于20,更新条件为{'$inc': {'age': 1}},执行以后会讲第一条符合条件的数据年龄加1。
condition = {'age': {"$gt": 20}}
result = collection.update_one(condition, {"$inc": {'age': 1}})
print(result)  # <pymongo.results.UpdateResult object at 0x0000020075E2BBC8>
print(result.matched_count, result.modified_count)  # 1 1

3 update_many

    update_many()方法会将全部符合条件的数据都更新。

condition = {'age': {"$gt": 20}}
result = collection.update_many(condition, {"$inc": {'age': 1}})
print(result)  #<pymongo.results.UpdateResult object at 0x000002076EA4BBC8>
print(result.matched_count, result.modified_count)  # 3 3

删除 

1 remove

    符合条件的全部数据均会被删除。

result = collection.remove({'name': 'ethan5'})
print(result)  # {'n': 1, 'ok': 1.0}

2 delete_one&delete_many

result = collection.remove({'name': 'ethan5'})
print(result)  # {'n': 1, 'ok': 1.0}
result = collection.delete_one({'name': 'ethan6'})
print(result)  # <pymongo.results.DeleteResult object at 0x00000212BF56CC08>
print(result.deleted_count)  # 1

result = collection.delete_many({'age': {'$lt': 25}})
print(result.deleted_count)  # 4

其它

    另外,pymongo还提供了一些组合方法,如find_one_and_delete()、find_one_and_replace()、find_one_and_update(),即查找后删除、替换和更新操做。

    对索引进行操做,如create_index()、create_indexes()、drop_index()等,详情见官方文档

相关文章
相关标签/搜索