python 读取单所有json数据写入mongodb(单个)
生活随笔
收集整理的這篇文章主要介紹了
python 读取单所有json数据写入mongodb(单个)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
<--------------主函數(shù)------------------->
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文件,根據(jù)關(guān)鍵字查詢
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}}) #根據(jù)ObjectID修改track
collection.update((id), {'$push': {'nodeindex': want_No}}) #根據(jù)ObjectID添加nodeindex
collection.update((id), {'$set': {'nodeindex': want_No}}) #根據(jù)ObjectID修改nodeindex ,去除多余的[]
id_change = collection.find_one(id) #調(diào)出修改后的數(shù)據(jù)
print("修改后:")
print(id_change)
if __name__ =='__main__':
mongoclient()
<---------------讀取文件代碼-----------------------> import json
def read(data, find):
# 設(shè)置以utf-8解碼模式讀取文件,encoding參數(shù)必須設(shè)置,否則默認(rèn)以gbk模式讀取文件,當(dāng)文件中包含中文時,會報錯
f = open(data, encoding='utf-8')
setting = json.load(f)
# 注意多重結(jié)構(gòu)的讀取語法
# family = setting['BaseSettings']['font']
style = setting[find]
# print(family)
return style
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文件,根據(jù)關(guān)鍵字查詢
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}}) #根據(jù)ObjectID修改track
collection.update((id), {'$push': {'nodeindex': want_No}}) #根據(jù)ObjectID添加nodeindex
collection.update((id), {'$set': {'nodeindex': want_No}}) #根據(jù)ObjectID修改nodeindex ,去除多余的[]
id_change = collection.find_one(id) #調(diào)出修改后的數(shù)據(jù)
print("修改后:")
print(id_change)
if __name__ =='__main__':
mongoclient()
<---------------讀取文件代碼-----------------------> import json
def read(data, find):
# 設(shè)置以utf-8解碼模式讀取文件,encoding參數(shù)必須設(shè)置,否則默認(rèn)以gbk模式讀取文件,當(dāng)文件中包含中文時,會報錯
f = open(data, encoding='utf-8')
setting = json.load(f)
# 注意多重結(jié)構(gòu)的讀取語法
# family = setting['BaseSettings']['font']
style = setting[find]
# print(family)
return style
轉(zhuǎn)載于:https://www.cnblogs.com/setname/p/7423497.html
總結(jié)
以上是生活随笔為你收集整理的python 读取单所有json数据写入mongodb(单个)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Recyclerview 出现 java
- 下一篇: 百度地图API详解之公交导航