码迷,mamicode.com
首页 > 数据库 > 详细

python 读取单所有json数据写入mongodb(单个)

时间:2017-08-24 16:13:45      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:ret   多重   data   中文   one   tin   for   stl   hang   

<--------------主函数------------------->

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(单个)

标签:ret   多重   data   中文   one   tin   for   stl   hang   

原文地址:http://www.cnblogs.com/setname/p/7423497.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!