- 简单的例子
#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,
})
- 数据导入和导出
-
数据导出
-导出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
中创建名为log
的collection
参考资料:
-1. Python下MongoDB入门学习. http://henan.leanote.com/post/Python%E4%B8%8BMongoDB%E5%85%A5%E9%97%A8%E5%AD%A6%E4%B9%A0
网友评论