MongoDB插入数据的三种办法,Python操作MongoDB数据库

作者: 韦德国际1946手机版  发布:2019-05-28

正文实例讲述了Python实现读取SQLServer数据并插入到MongoDB数据库的法子。分享给我们供我们参照他事他说加以侦察,具体如下:

# -*- coding: utf-8 -*-
import pyodbc
import os
import csv
import pymongo
from pymongo import ASCENDING, DESCENDING
from pymongo import MongoClient
import binascii

本文实例讲述了Python操作MongoDB数据库的措施。分享给我们供我们参谋,具体如下:

insert()方法:
    上面是在inventory集合中插入叁个八个字段的文书档案:        

# -*- coding: utf-8 -*-
import pyodbc
import os
import csv
import pymongo
from pymongo import ASCENDING, DESCENDING
from pymongo import MongoClient
import binascii
'''连接mongoDB数据库'''
client = MongoClient('10.20.4.79', 27017)
#client = MongoClient('10.20.66.106', 27017)
db_name = 'SoftADoutput'
db = client[db_name]
'''连接SqlServer数据库'''
connStr = 'DRIVER={SQL Server Native Client 11.0};SERVER=DESKTOP-44P34L6;DATABASE=Softput;UID=sa;PWD=sa'
conn = pyodbc.connect(connStr)
cursor = conn.cursor()
#########################################Channel_CovCode数据插入##########################
'''从SQLServer数据库读取Channel_CovCode数据写入到mongodb数据库中Channel_CovCode集合中'''
def InsertChannel_CovCode(cursor):
  cursor.execute("select dm, ms from channel_CovCode")
  rows = cursor.fetchall()
  i = 1
  for row in rows:#gb18030
    db.channel_CovCode.insert({'_id':i,'dm':row.dm,'ms':row.ms.decode('gbk').encode('utf-8')})
    i = i   1
InsertChannel_CovCode(cursor)
#############################################################################################
#########################################channel_ModeCode数据插入#############################
'''从SQLServer数据库读取channel_ModeCode数据写入到mongodb数据库中channel_ModeCode集合中'''
def InsertChannel_ModeCode(cursor):
  cursor.execute("select dm, ms from channel_ModeCode")
  rows = cursor.fetchall()
  i = 1
  for row in rows:#gb18030
    db.channel_ModeCode.insert({'_id':i,'dm':row.dm,'ms':row.ms.decode('gbk').encode('utf-8')})
    i = i   1
InsertChannel_ModeCode(cursor)
#############################################################################################
#########################################citynumb数据插入########################
'''从SQLServer数据库读取citynumb数据写入到mongodb数据库中citynumb集合中'''
def InsertCitynumb(cursor):
  cursor.execute("select t.XZQMC,t.SMC,t.CSMC,t.SSQYDM,t.CITY_E,t.AREA_E,t.PROV_E from citynumb t")
  rows = cursor.fetchall()
  i = 1
  for row in rows:
    xzqmc = row.XZQMC
    if xzqmc != None:
      xzqmc = xzqmc.decode('gbk').encode('utf-8')
    smc = row.SMC
    if smc != None:
      smc = smc.decode('gbk').encode('utf-8')
    csmc = row.CSMC
    if csmc != None:
      csmc = csmc.decode('gbk').encode('utf-8')
    db.citynumb.insert({'_id':i,'XZQMC':xzqmc,'SMC':smc,'CSMC':csmc,'SSQYDM':row.SSQYDM,'CITY_E':row.CITY_E,'AREA_E':row.AREA_E,'PROV_E':row.PROV_E})
    i = i   1
InsertCitynumb(cursor)
##################################################################################################################
#########################################channel数据插入############################
'''从SQLServer数据库读取channel数据写入到mongodb数据库中channel集合中'''
def InsertChannel(cursor):
  cursor.execute("select pdcmc,pdemc,pdemcj,pdbm1,ssqydm,cov,sdate,mode,startTime,endTime,memo,pdtype,sflag,edate,corporation from channel")
  rows = cursor.fetchall()
  i = 1
  for r in rows:
    pdcmc = r.pdcmc
    if pdcmc != None:
      pdcmc = pdcmc.decode('gbk').encode('utf-8')
    memo = r.memo
    if memo != None:
      memo = memo.decode('gbk').encode('utf-8')
    corporation = r.corporation
    if corporation != None:
      corporation = corporation.decode('gbk').encode('utf-8')
    db.channel.insert({'_id':i,'pdcmc':pdcmc,'pdemc':r.pdemc,'pdemcj':r.pdemcj,'pdbm1':r.pdbm1,'ssqydm':r.ssqydm,'cov':r.cov,'sdate':r.sdate,'mode':r.mode,'startTime':r.startTime,'endTime':r.endTime,'memo':memo,'pdtype':r.pdtype,'sflag':r.sflag,'edate':r.edate,'corporation':corporation})
    i = i   1
InsertChannel(cursor)
#############################################################################################
#########################################CPBZK数据插入############################
'''从SQLServer数据库读取CPBZK数据写入到mongodb数据库中CPBZK集合中'''
def InsertCPBZK(cursor):
  cursor.execute("select ZTC,EZTC,ZTC_CODE,LBDM,B_CODE,QY_CODE,IChange,cla from CPBZK")
    rows = cursor.fetchall()
    i = 1
    for r in rows:#gb18030
      ztc = r.ZTC
      if ztc != None:
        ztc = ztc.decode('gbk').encode('utf-8')
      db.CPBZK.insert({'_id':i,'ZTC':ztc,'EZTC':r.EZTC,'ZTC_CODE':r.ZTC_CODE,'LBDM':r.LBDM,'B_CODE':r.B_CODE,'QY_CODE':r.QY_CODE,'IChange':r.IChange,'cla':r.cla})
      i = i   1
InsertCPBZK(cursor)
#############################################################################################
#########################################TVPGMCLASS数据插入##########################
'''从SQLServer数据库读取TVPGMCLASS数据写入到mongodb数据库中TVPGMCLASS集合中'''
def InsertTVPGMCLASS(cursor):
  cursor.execute("select ClassChDesc,ClassEnDesc,ClassCode,ParentCode,SortNo from TVPGMCLASS")
  rows = cursor.fetchall()
  i = 1
  for r in rows:#gb18030
    classChDesc = r.ClassChDesc
    if classChDesc != None:
      classChDesc = classChDesc.decode('gbk').encode('utf-8')
    db.TVPGMCLASS.insert({'_id':i,'ClassChDesc':classChDesc,'ClassEnDesc':r.ClassEnDesc,'ClassCode':r.ClassCode,
'ParentCode':r.ParentCode,'SortNo':r.SortNo})
    i = i   1
InsertTVPGMCLASS(cursor)
#############################################################################################
#########################################GGBZK_DESCRIPTION数据插入###########################
'''从SQLServer数据库读取GGBZK_DESCRIPTION数据写入到mongodb数据库中GGBZK_DESCRIPTION集合中'''
def InsertGGBZK_DESCRIPTION(cursor):
  cursor.execute("select V_code,des_named,des_main,des_background,des_scene,des_words,ModifyFlag,UpdateDate from  GGBZK_DESCRIPTION")
  rows = cursor.fetchall()
  i = 1
  for r in rows:#gb18030
    name = r.des_named
    if name != None:
      name = name.decode('gbk').encode('utf-8')
    desmain = r.des_main
    if desmain != None:
      desmain = desmain.decode('gbk').encode('utf-8')
    background = r.des_background
    if background != None:
      background = background.decode('gbk').encode('utf-8')
    scene = r.des_scene
    if scene != None:
      scene = scene.decode('gbk').encode('utf-8')
    words = r.des_words
    if words != None:
      words = words.decode('gbk').encode('utf-8')
    db.GGBZK_DESCRIPTION.insert({'_id':i,'V_code':r.V_code,'des_named':name,'des_main':desmain,'des_background':background,
'des_scene':scene,'des_words':words,'ModifyFlag':r.ModifyFlag,'UpdateDate':r.UpdateDate})
    i = i   1
InsertGGBZK_DESCRIPTION(cursor)
#########################################Z201607_027数据插入##########################
'''从SQLServer数据库读取Z201607_027数据写入到mongodb数据库中Z201607_027集合中'''
def InsertZ201607_027(cursor):
  strSql = "select PD,RQ,SHIJIAN,ENDSHIJIAN,LBDM,ZTC_CODE,V_CODE,B_CODE,QY_CODE,QUANLITY,SPECIAL,LANGUAGE,LENGTH,SLENGTH,QJM1,QJM2,QGG,HJM1,HJM2,HGG,DUAN,OSHIJIAN,JG,SORTNO,LURU,ZFILE,COST,ROWTS,COST1,COST2,COST3 from Z201607_027"
  cursor.execute(strSql)
  rows = cursor.fetchall()
  i = 1
  for r in rows:#gb18030
    cost = float(r.COST) #COST money类型
    cost1 = float(r.COST1)
    cost2 = float(r.COST2)
    cost3 = float(r.COST3)
    #先把时间戳转为字符串,然后再转为十进制数
    rowts = int(str(binascii.b2a_hex(r.ROWTS)),16)
    luru = r.LURU
    if luru != None:
      luru = luru.decode('gbk').encode('utf-8')
    vCODE = r.V_CODE
    if vCODE != None:
      vCODE = vCODE.decode('gbk').encode('utf-8')
    db.Z201607_027.insert({'_id':i,'PD':r.PD,'RQ':r.RQ,'SHIJIAN':r.SHIJIAN,'ENDSHIJIAN':r.ENDSHIJIAN,'LBDM':r.LBDM,
'ZTC_CODE':r.ZTC_CODE,'V_CODE':vCODE,'B_CODE':r.B_CODE,'QY_CODE':r.QY_CODE,'QUANLITY':r.QUANLITY,
'SPECIAL':r.SPECIAL,'LANGUAGE':r.LANGUAGE,'LENGTH':r.LENGTH,'SLENGTH':r.SLENGTH,'QJM1':r.QJM1,'QJM2':r.QJM2,'QGG':r.QGG,'HJM1':r.HJM1,'HJM2':r.HJM2,'HGG':r.HGG,'DUAN':r.DUAN,'OSHIJIAN':r.OSHIJIAN,'JG':r.JG,'SORTNO':r.SORTNO,'LURU':luru,'ZFILE':r.ZFILE,
'COST':cost,'ROWTS':rowts,'ExpandProperty':'','COST1':cost1,'COST2':cost2,'COST3':cost3})
    i = i   1
InsertZ201607_027(cursor)
#############################################################################################

MongoDB插入数据的三种办法,Python操作MongoDB数据库的诀窍言传身教。 

>>> import pymongo
>>> client=pymongo.MongoClient ('localhost',27017)
>>> db=client.students
>>> db.collection_names()
['students']
>>> students=db.students
>>> students.find()
<pymongo.cursor.Cursor object at 0x0000017A74305FD0>
>>> for item in students.find():
  print(item)
{'_id': ObjectId('59394a87ae09c56bd9c1d375'), 'name': 'zhangsan', 'age': 18.0, 'sex': 'male'}
>>> wangwu={'name':'wangwu','age':20,'sex':'male'}
>>> students.insert(wangwu)
ObjectId('593a7c5fedb5a1abeb757052')
>>> for item in students.find({'name':'wangwu'}):
  print(item)
{'_id': ObjectId('593a7c5fedb5a1abeb757052'), 'name': 'wangwu', 'age': 20, 'sex': 'male'}
>>> students.find_one()
{'_id': ObjectId('59394a87ae09c56bd9c1d375'), 'name': 'zhangsan', 'age': 18.0, 'sex': 'male'}
>>> students.find_one({'name':'wangwu'})
{'_id': ObjectId('593a7c5fedb5a1abeb757052'), 'name': 'wangwu', 'age': 20, 'sex': 'male'}
>>> students.find().count()
2
>>> students.remove({'name':'wangwu'})
{'ok': 1, 'n': 1}
>>> for item in students.find():
  print(item)
{'_id': ObjectId('59394a87ae09c56bd9c1d375'), 'name': 'zhangsan', 'age': 18.0, 'sex': 'male'}
>>> students.find().count()
1
>>> students.create_index([('name',pymongo.ASCENDING)])
'name_1'
>>> students.update({'name':'zhangsan'},{'$set':{'age':25}})
{'ok': 1, 'nModified': 1, 'n': 1, 'updatedExisting': True}
>>> students.find_one()
{'_id': ObjectId('59394a87ae09c56bd9c1d375'), 'name': 'zhangsan', 'age': 25, 'sex': 'male'}
>>> students.update({'age':25},{'$set':{'sex':'Female'}})
{'ok': 1, 'nModified': 1, 'n': 1, 'updatedExisting': True}
>>> students.remove()
{'ok': 1, 'n': 1}
>>> students.find().count()
0
>>> zhangsan={'name':'zhangsan','age':25,'sex':'Male'}
>>> lisi={'name':'lisi','age':21,'sex':'Male'}
>>> wangwu={'name':'wangwu','age':22,'sex':'Female'}
>>> students.insert_many([zhangsan,lisi,wangwu])
<pymongo.results.InsertManyResult object at 0x0000017A749FC5E8>
>>> for item in students.find().sort('name',pymongo.ASCENDING):
  print(item)
{'_id': ObjectId('593a806bedb5a1abeb757054'), 'name': 'lisi', 'age': 21, 'sex': 'Male'}
{'_id': ObjectId('593a806bedb5a1abeb757055'), 'name': 'wangwu', 'age': 22, 'sex': 'Female'}
{'_id': ObjectId('593a806bedb5a1abeb757053'), 'name': 'zhangsan', 'age': 25, 'sex': 'Male'}
>>> for item in students.find().sort([('sex',pymongo.DESCENDING),('name',pymongo.ASCENDING)]):
  print(item)
{'_id': ObjectId('593a806bedb5a1abeb757054'), 'name': 'lisi', 'age': 21, 'sex': 'Male'}
{'_id': ObjectId('593a806bedb5a1abeb757053'), 'name': 'zhangsan', 'age': 25, 'sex': 'Male'}
{'_id': ObjectId('593a806bedb5a1abeb757055'), 'name': 'wangwu', 'age': 22, 'sex': 'Female'}
>>>

复制代码 代码如下:

更加多关于Python相关内容感兴趣的读者可查看本站专项论题:《Python常见数据库操作手艺汇总》、《Python编码操作技艺总计》、《Python图片操作技艺计算》、《Python数据结构与算法教程》、《Python Socket编制程序本领计算》、《Python函数使用本领计算》、《Python字符串操作技术汇总》、《Python入门与进级经典教程》及《Python文件与目录操作才具汇总》

'''连接mongoDB数据库'''
client = MongoClient('10.20.4.79', 27017)
#client = MongoClient('10.20.66.106', 27017)
db_name = 'SoftADoutput'
db = client[db_name]

越多关于Python相关内容感兴趣的读者可查看本站专项论题:《Python常见数据库操作工夫汇总》、《Python数学生运动算技能总结》、《Python数据结构与算法教程》、《Python函数使用技能计算》、《Python字符串操作本领汇总》、《Python入门与进级卓绝教程》及《Python文件与目录操作技术汇总》

db.inventory.insert( { _id: 10, type: "misc", item: "card", qty: 15 } )

可望本文所述对我们Python程序设计具备帮助。

'''连接SqlServer数据库'''
connStr = 'DRIVER={SQL Server Native Client 11.0};SERVER=DESKTOP-44P34L6;DATABASE=Softput;UID=sa;PWD=sa'
conn = pyodbc.connect(connStr)
cursor = conn.cursor()
#########################################Channel_CovCode数据插入##########################
'''从SQLServer数据库读取Channel_CovCode数据写入到mongodb数据库中Channel_CovCode集合中'''
def InsertChannel_CovCode(cursor):
  cursor.execute("select dm, ms from channel_CovCode")
  rows = cursor.fetchall()
  i = 1
  for row in rows:#gb18030
    db.channel_CovCode.insert({'_id':i,'dm':row.dm,'ms':row.ms.decode('gbk').encode('utf-8')})
    i = i 1

瞩望本文所述对大家Python程序设计具有扶助。

        在实示例中,文书档案有一个用户钦赐的值为10的_id字段,这么些值必须在inventory会集中无可比拟。
update()方法:
    调用update()方法运用upsert标记创立二个新文书档案当未有相称查询条件的文书档案时。下边包车型地铁例子当inventory集合中从未包涵{type:"books",item:"journal"}的文书档案时创建贰个新文书档案:

您可能感兴趣的小说:

  • Python连接mssql数据库编码难题消除措施
  • Python基于Pymssql模块实现接二连三SQL Server数据库的法子详解
  • Python版Mssql爆破小本子
  • 怎么管理Python叁.肆 使用pymssql 乱码难点
  • Python3连接SQLServer、Oracle、MySql的方法
  • Python操作Sql Server 二〇一〇数据库的艺术详解
  • Python三操作SQL Server数据库(实例讲明)
  • python访问sqlserver示例
  • python连接sql server乱码的消除方法
  • Python完成的连日mssql数据库操作示例

InsertChannel_CovCode(cursor)
#############################################################################################

你大概感兴趣的小说:

  • Python使用pymongo模块操作MongoDB的艺术言传身教
  • Python pymongo模块用法示例
  • Python的MongoDB模块PyMongo操作方法集锦
  • Python操作MongoDB数据库PyMongo库使用格局
  • Python三中选拔PyMongo的章程详解
  • Python三装置Pymongo详细步骤
  • python之PyMongo使用计算
  • Python常见MongoDB数据库操作实例总结
  • Python操作mongodb的9个步骤
  • Python pymongo模块常用操作分析

      

#########################################channel_ModeCode数据插入#############################
'''从SQLServer数据库读取channel_ModeCode数据写入到mongodb数据库中channel_ModeCode集合中'''
def InsertChannel_ModeCode(cursor):
  cursor.execute("select dm, ms from channel_ModeCode")
  rows = cursor.fetchall()
  i = 1
  for row in rows:#gb18030
    db.channel_ModeCode.insert({'_id':i,'dm':row.dm,'ms':row.ms.decode('gbk').encode('utf-8')})
    i = i 1

复制代码 代码如下:

InsertChannel_ModeCode(cursor)
#############################################################################################

db.inventory.update(
                         { type: "book", item : "journal" },
                         { $set :     { qty: 10 } },
                         { upsert :true     }
                )

#########################################citynumb数据插入########################
'''从SQLServer数据库读取citynumb数据写入到mongodb数据库中citynumb集结中'''
def InsertCitynumb(cursor):
  cursor.execute("select t.XZQMC,t.SMC,t.CSMC,t.SSQYDM,t.CITY_E,t.AREA_E,t.PROV_E from citynumb t")
  rows = cursor.fetchall()
  i = 1
  for row in rows:
    xzqmc = row.XZQMC
    if xzqmc != None:
      xzqmc = xzqmc.decode('gbk').encode('utf-8')

 MongoDB添加_id字段和分配三个唯1的ObjectId作为它的值。新文书档案包括来自己检查询<query>条件的item和type字段,和来源立异<update>参数的qty字段:       

    smc = row.SMC
    if smc != None:
      smc = smc.decode('gbk').encode('utf-8')

复制代码 代码如下:

本文由韦德国际1946发布于韦德国际1946手机版,转载请注明出处:MongoDB插入数据的三种办法,Python操作MongoDB数据库

关键词: python