用 Python 将文本文件传存到 MongoDB

用 Python 将文本文件传存到 MongoDB #

之前有一些文件使用的是 “|” 分割的,類似如下:

Python|Language|Dynamic

需要轉移到 MongoDB 中,Python 腳本如下:

import pymongo
import os

client = pymongo.MongoClient("mongodb://localhost:27017")
mydb = client\["language\_db"\]
mytable = mydb\["language\_info"\]

with open('infos') as f:
    file\_data = f.readlines()

file\_info\_list = \[\]

for item in file\_data:
    dl = item.split('|')
    d = dict()
    d\['language\_name'\] = dl\[1\]
    d\['language'\] = dl\[2\]
    d\['language\_type'\] = dl\[3\]
    file\_info\_list.append(d)

x = mytable.insert\_many(file\_info\_list)

之後還有多字段查詢啥的以後慢慢更新了~