美文网首页
【爬虫】-003-MongoDB入门

【爬虫】-003-MongoDB入门

作者: 9756a8680596 | 来源:发表于2017-12-26 17:02 被阅读14次
    1. 简单的例子
    #coding: utf-8
    from pymongo import MongoClient
    
    host = 'localhost'
    port = 27017
    
    client = MongoClient(host, port)    #  访问服务器和对应端口,创建一个connection对象
    db = client['test']                 #   创建名为test的数据库,也可以写成 db = client.test
    sheet = db['sheet']                 #   在 数据库 中 创建名为sheet的表,也可以写成 sheet = db.sheet
    for i in range(101):
        print(i)
        sheet.insert_one({  #
                'name': 'name' + str(i),
                'age': i,
            })
    
    1. 数据导入和导出
    • 数据导出
      -导出JSON文件:mongoexport -d local -c startup_log -o startup_log.json
      -导出csv文件:mongoexport -d local -c startup_log --type=csv -f _id,hostname,startTime,pid -o startup_log.csv
      -其中,
      -d表示数据库
      -c表示所选择的collection
      -o表示目标文件
      -f指定csv数据列
      --type=csv指定数据格式为csv

    • 数据导入
      -导入csv文件:mongoimport -d local -c log --type csv --headerline --file startup_log.csv
      -导入JSON文件mongoimport -d local -c log --file startup_log.json
      -其中,
      --headerline表示忽略表头
      db.createCollection('log')local中创建名为logcollection


    参考资料:
    -1. Python下MongoDB入门学习. http://henan.leanote.com/post/Python%E4%B8%8BMongoDB%E5%85%A5%E9%97%A8%E5%AD%A6%E4%B9%A0

    相关文章

      网友评论

          本文标题:【爬虫】-003-MongoDB入门

          本文链接:https://www.haomeiwen.com/subject/lhhjgxtx.html