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


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

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM