1. 程式人生 > >python 讀取單所有json數據寫入mongodb(單個)

python 讀取單所有json數據寫入mongodb(單個)

pytho mongod nod from mon eset fin 註意 $set

<--------------主函數------------------->

from pymongo import MongoClient
from bson.objectid import ObjectId
from read_json import read



def mongoclient():
client = MongoClient(‘127.0.0.1‘, 27017)
db = client.test
collection = db.test
# collection.insert({})
# for i in collection.find({"name":"樂清市東岸北段"}):
# print(i)
data = (‘coastlines.real.json‘)
find_Da = (‘track‘)
find_Id = (‘coastlineid‘)
find_Node = (‘nodes_index‘)

want_Data = read(data, find_Da) #傳入json文件,根據關鍵字查詢
want_Id = read(data, find_Id)
want_No = read(data, find_Node)
id = {‘_id‘: ObjectId(want_Id)}
id_print = collection.find_one(id)
print(id_print)

collection.update((id), {‘$set‘: {‘track‘: want_Data}}) #根據ObjectID修改track
collection.update((id), {‘$push‘: {‘nodeindex‘: want_No}}) #根據ObjectID添加nodeindex
collection.update((id), {‘$set‘: {‘nodeindex‘: want_No}}) #根據ObjectID修改nodeindex ,去除多余的[]


id_change = collection.find_one(id) #調出修改後的數據
print("修改後:")
print(id_change)




if __name__ ==‘__main__‘:
mongoclient()

<---------------讀取文件代碼----------------------->
import json

def read(data, find):
# 設置以utf-8解碼模式讀取文件,encoding參數必須設置,否則默認以gbk模式讀取文件,當文件中包含中文時,會報錯
f = open(data, encoding=‘utf-8‘)
setting = json.load(f)

# 註意多重結構的讀取語法
# family = setting[‘BaseSettings‘][‘font‘]
style = setting[find]


# print(family)
return style

python 讀取單所有json數據寫入mongodb(單個)