一.开始使用数据库MongoDB

开始使用数据库MongoDB

  1. 给数据库命名:
client = pymongo.MongoClient('localhost',27017)
walden = client['walden']   #左边的是在python中使用的对象,右边的是在数据库中同步建立的对象
  1. 在文件下创建表单:
sheet_tab = walden['sheet_tab']
  1. 往数据库中写入数据:
path = 'c:/Users/asus-pc/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)  #关键是这一步
  1. 展示数据库中的数据:
for item in sheet_tab.find():
        print(item)
  1. 数据库的操作:
for item in sheet_tab.find({'words':0}): #筛选出所有words值=0的数据并打印
        print(item)
for item in sheet_tab.find():  #打印所有line属性数据
        print(item['line'])
# $lt/$lte/$gt/$gte/$ne,依次等价于</<=/>/>=/!=。(l表示less g表示greater e表示equal n表示not)
for item in sheet_tab.find({'words':{'$lt':5}}):    #筛选出所有words值小于的数据并打印
        print(item)

完整代码

import pymongo
client = pymongo.MongoClient('localhost',27017)
walden = client['walden']   #左边的是在python中使用的对象,右边的是在数据库中同步建立的对象

path = 'c:/Users/asus-pc/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)  #关键是这一步

for item in sheet_tab.find():
        print(item)

for item in sheet_tab.find({'words':0}): #筛选出所有words值=0的数据并打印
        print(item)
for item in sheet_tab.find():  #打印所有line属性数据
        print(item['line'])
# $lt/$lte/$gt/$gte/$ne,依次等价于</<=/>/>=/!=。(l表示less g表示greater e表示equal n表示not)
for item in sheet_tab.find({'words':{'$lt':5}}):    #筛选出所有words值小于的数据并打印
        print(item)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,878评论 0 23
  • 编译环境:python v3.5.0, mac osx 10.11.4 python爬虫基础知识: Python...
    掷骰子的求阅读 16,659评论 11 101
  • 买房子的事情终究是杳无音信,算了,我也不管了,随便吧。优点越来越不是优点,缺点越来越突出。 有些顾虑,讲出来,心就...
    蔓越梅小丸子阅读 103评论 0 0
  • 苏打绿 《夏·狂热》 总能想起童年阴影魔方大厦 社会光怪陆离 要清醒自己的模样 雷响得放肆 死去活来坚持 抛空了理...
    口天雨雨齐阅读 488评论 0 1
  • 我是一只狗。 我看到自己的狗血,混着雨水,在地上盛开出了一朵巨大的玫瑰,娇艳欲滴! 我被车撞了。我真不是为了碰瓷,...
    南乔樾树阅读 213评论 0 0