python --MongoDB(文档型数据库)

import  pymongo

client= pymongo.MongoClient(host='localhost',port=27017)
# client=MongoClient('mongodb://localhost:27017/')

#指定数据库
db=client.test
#db=client['test']

##指定集合(collection)
collection =db.students  # collection=db['students']

student = {
    'id': '20170101',
    'name': 'Jordan',
    'age': 20,
    'gender': 'male'
}

result = collection.insert(student)
print(result)
'''
在MongoDB中,每条数据其实都有一个_id属性来唯一标识。如果没有显式指明该属性,
MongoDB会自动产生一个ObjectId类型的_id属性。insert()方法会在执行后返回_id值。
也可以同时插入多条数据,只需要以列表形式传递即可
result = collection.insert([student1, student2])
print(result)
返回结果是对应的_id的集合:

[ObjectId('5932a80115c2606a59e8a048'), ObjectId('5932a80115c2606a59e8a049')]
PyMongo 3.x版本中,官方已经不推荐使用insert()方法了。当然,继续使用也没有什么问题。
官方推荐使用insert_one()和insert_many()方法来分别插入单条记录和多条记录,
result = collection.insert_one(student)
print(result) //<pymongo.results.InsertOneResult object at 0x10d68b558>
print(result.inserted_id) //5932ab0f15c2606f0c1cf6c5

result = collection.insert_many([student1, student2])
print(result)  //<pymongo.results.InsertManyResult object at 0x101dea558>
print(result.inserted_ids)// [ObjectId('5932abf415c2607083d3b2ac'), ObjectId('5932abf415c2607083d3b2ad')]

'''
##查询
'''利用find_one()或find()方法进行查询,其中find_one()查询得到的是单个结果,find()则返回一个生成器对象。、
当然,如果查询结果不存在,则会返回None。
name为Mike的数据,它的返回结果是字典类型,

result = collection.find_one({'name': 'Mike'})
print(type(result))
print(result)
//<class 'dict'>
//{'_id': ObjectId('5932a80115c2606a59e8a049'), 'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male'}
根据ObjectId来查询,此时需要使用bson库里面的objectid
from bson.objectid import ObjectId
result = collection.find_one({'_id': ObjectId('593278c115c2602667ec6bae')})

如果要查询年龄大于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]}}

$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'}自身粉丝数等于关注数

##计数
count = collection.find().count()
count = collection.find({'age': 20}).count()
'''
##排序

results = collection.find().sort('name', pymongo.ASCENDING) # pymongo.DESCENDING降序 pymongo.ASCENDING升序
print([result['name'] for result in results])
#  ['Harden', 'Jordan', 'Kevin', 'Mark', 'Mike']
##偏移
results = collection.find().sort('name', pymongo.ASCENDING).skip(2)
print([result['name'] for result in results])
#['Kevin', 'Mark', 'Mike']

##限制
results = collection.find().sort('name', pymongo.ASCENDING).skip(2).limit(2)
print([result['name'] for result in results])
#['Kevin', 'Mark']

##更新
condition ={'name':'Kevin'}
student=collection.find_one(condition)
student['age']=25
result=collection.update(condition,student)
print(result) #     {'ok': 1, 'nModified': 1, 'n': 1, 'updatedExisting': True}
#alse
result = collection.update(condition, {'$set': student})
# 只更新student字典内存在的字段。如果原先还有其他字段,则不会更新,也不会删除。
# 而如果不用$set的话,则会把之前的数据全部用student字典替换;如果原本存在其他字段,则会被删除。
'''
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条
'''

##删除
result = collection.remove({'name': 'Kevin'})
print(result)# {'ok': 1, 'n': 1}


result = collection.delete_one({'name': 'Kevin'})
print(result)
print(result.deleted_count)
result = collection.delete_many({'age': {'$lt': 25}})
print(result.deleted_count)
'''
其他操作
另外,PyMongo还提供了一些组合方法,如find_one_and_delete()、find_one_and_replace()和find_one_and_update(),
它们是查找后删除、替换和更新操作,其用法与上述方法基本一致。
另外,还可以对索引进行操作,相关方法有create_index()、create_indexes()和drop_index()等。
'''
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值