import pymongo
client = pymongo.MongoClient(host='localhost',port=27017)#连接数据库
#db = client.test#指定数据库为test
#给数据库起一个名字
'''
###################比较符号归纳########################
符 号 含 义 示 例
..................................................
$lt 小于 {'age':{'$lt':23}}
$gt 大于 {'age':{'$gt':23}}
$lte 小于等于 {'age':{'$lte':23}}
$gte 大于等于 {'age':{'$gte':23}}
$ne 不等于 {'age':{'$ne':23}}
$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'}自身粉丝数等于关注数
'''
def sheet_tab():#指定数据库
walden=client['walden']#左边是我们操作的对象,右边同步建立
sheet_tab = walden['sheet_tab']#创建一页
return sheet_tab
def insert_one():#插入数据{insert_one(),insert_many()}
#打开文件
path = 'walden.txt'
with open(path,'r') as f:
lines = f.readlines()
#构建数据字典
for index,line in enumerate(lines):
data={
'index':index,
'line':line,
'words':len(line.split())
}
sheet_tab.insert_one(data)
def show(sheet_tab):#查询{find(),find_one()},计数{.count()}
for item in sheet_tab.find({}):
print(item['line'])
count = sheet_tab.find().count()
print(count)
def delete(sheet_tab):#delete_one(),delete_many()
res=sheet_tab.delete_many({'words':0})
print(res.deleted_count)
def sort(collection):#排序{sort()},忽略前两个元素skip(),返回前两个结果limit()
results = collection.find().sort('words', pymongo.ASCENDING)
print([result['line'] for result in results]) # 升序输出
res = collection.find().sort('words', pymongo.ASCENDING).skip(2) # 忽略前两个元素
print([result['line'] for result in res])
res_limit = collection.find().sort('words', pymongo.ASCENDING).skip(2).limit(2) # 先偏移,再返回前两个结果
print([result['line'] for result in res_limit])
def updata(collection):#update_one()方法和update_many()
line='this test with updata---this test with updata---this test with updata---this test with updata---this test with updata---this test with updata'
condition = {'index':0}
old = collection.find_one(condition)
old['line'] = '5b96291104cdab1e8c2d365b'
result = collection.update_one(condition, {'$set': old})
print(result)
print(result.matched_count, result.modified_count)
###这里我们要更新index为0的数据的line:首先指定查询条件,然后将数据查询出来,修改line后调用update()方法将原条件和修改后的数据传入。
if __name__ == '__main__':
updata(sheet_tab())