MongoDB数据创建与使用

MongoDB数据创建与使用


创建数据库
代码功能:读取本地文本文件,并保存到数据库中

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()

#从表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}})

数据库表的备份

  • 显示所有数据库
show dbs
  • 使用数据库
use dbname
  • 创建数据表
db.createCollection('表名')  
  • 备份数据表
db.表x.copyTo('表y')
原文地址:https://www.cnblogs.com/zwer/p/10462121.html