建立數據庫
代碼功能:讀取本地文本文件,並保存到數據庫中sql
import pymongo #鏈接mongo數據庫 client = pymongo.MongoClient('localhost',27017) #建立數據庫 walden = client['walden'] #建立表 sheet_tab = walden['sheet_tab'] path= 'C:/Users/Lenovo/Desktop/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) # $lt/$lte/$gt/$gte/$ne,依次等價於</<=/>/>=/!=。(l表示less g表示greater e表示equal n表示not ) # for item in sheet_tab.find({'words':{'$lt':5}}): # print((item['line'])) for i in sheet_tab.find(): print(i['line'])
數據庫表的查找
mognodb上存放的表是以字典的形式存放,因此能夠經過
表名.find()進行查找數據庫
更新數據庫表 ——–update_one()ruby
#從表shouji中,去掉'-',並修改成'地點未知' for i in shouji.find(): if i['place'] == ' - ': place = '地點未知' else: place = i['place'] #對錶進行更新操做update,id表明位置,後面根據$set改變字段的值 shouji.update_one({'_id':i['_id']},{'$set':{'place':place}})
數據庫表的備份bash
show dbs
use dbname
db.createCollection('表名')
db.表x.copyTo('表y')