MySQL實現(xiàn)批量推送數(shù)據(jù)到Mongo
import pymongo import mysql.connector
連接MySQL數(shù)據(jù)庫
mysql_conn = mysql.connector.connect( host="localhost", user="yourusername", password="yourpassword", database="yourdatabase" )
連接MongoDB數(shù)據(jù)庫
mongo_client = pymongo.MongoClient("mongodb://localhost:27017/") mongo_db = mongo_client["mydatabase"] mongo_collection = mongo_db["mycollection"]在MongoDB中為指定集合創(chuàng)建索引
mongo_collection.create_index([("myfield", pymongo.ASCENDING)])緩沖列表和計數(shù)器以在每10000行處理后進行批處理
bulk_data = [] bulk_count = 0
創(chuàng)建游標(biāo)對象并從MySQL數(shù)據(jù)庫檢索數(shù)據(jù)
mysql_cursor = mysql_conn.cursor() mysql_cursor.execute("SELECT * FROM mytable")遍歷結(jié)果集并處理每個行。
for row in mysql_cursor: # 將一條記錄轉(zhuǎn)換成你的MongoDB文檔,然后將其添加到緩沖列表。
doc = { "myfield": row[0], "anotherfield": row[1], "yetanotherfield": row[2] } bulk_data.append(doc) bulk_count += 1# 如果我們達到了10000,請在集合中批量插入緩沖數(shù)據(jù)。
if bulk_count == 10000:
mongo_collection.insert_many(bulk_data)
# 重置計數(shù)器并清除緩沖數(shù)據(jù)列表
bulk_count = 0
bulk_data.clear()處理剩余的行,如果有任何事情需要處理。
if bulk_count > 0: mongo_collection.insert_many(bulk_data)
關(guān)閉MySQL連接。
mysql_conn.close()
import pymongo
import mysql.connector
# 連接MySQL數(shù)據(jù)庫
mysql_conn = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
# 連接MongoDB數(shù)據(jù)庫
mongo_client = pymongo.MongoClient("mongodb://localhost:27017/")
mongo_db = mongo_client["mydatabase"]
mongo_collection = mongo_db["mycollection"]
# 在MongoDB中為指定集合創(chuàng)建索引
mongo_collection.create_index([("myfield", pymongo.ASCENDING)])
# 緩沖列表和計數(shù)器以在每10000行處理后進行批處理
bulk_data = []
bulk_count = 0
# 創(chuàng)建游標(biāo)對象并從MySQL數(shù)據(jù)庫檢索數(shù)據(jù)
mysql_cursor = mysql_conn.cursor()
mysql_cursor.execute("SELECT * FROM mytable")
# 遍歷結(jié)果集并處理每個行。
for row in mysql_cursor:
# 將一條記錄轉(zhuǎn)換成你的MongoDB文檔,然后將其添加到緩沖列表。
doc = {
"myfield": row[0],
"anotherfield": row[1],
"yetanotherfield": row[2]
}
bulk_data.append(doc)
bulk_count += 1
# 如果我們達到了10000,請在集合中批量插入緩沖數(shù)據(jù)。
if bulk_count == 10000:
mongo_collection.insert_many(bulk_data)
# 重置計數(shù)器并清除緩沖數(shù)據(jù)列表
bulk_count = 0
bulk_data.clear()
# 處理剩余的行,如果有任何事情需要處理。
if bulk_count > 0:
mongo_collection.insert_many(bulk_data)
# 關(guān)閉MySQL連接。
mysql_conn.close()到此這篇關(guān)于MySQL實現(xiàn)批量推送數(shù)據(jù)到Mongo的文章就介紹到這了,更多相關(guān)MySQL推送數(shù)據(jù)到Mongo內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
linux系統(tǒng)中mysql數(shù)據(jù)庫的導(dǎo)入和導(dǎo)出
本文給大家簡單記錄了一下在linux系統(tǒng)中mysql數(shù)據(jù)庫的導(dǎo)入和導(dǎo)出的方法,有相同需求的小伙伴可以參考下2016-02-02
jdbc連接mysq之serverTimezone設(shè)定方式
這篇文章主要介紹了jdbc連接mysq之serverTimezone設(shè)定方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-01-01
mysql 5.7.13 安裝配置方法圖文教程(linux)
這篇文章主要為大家詳細(xì)介紹了linux下mysql 5.7.13 安裝配置方法圖文教程,感興趣的小伙伴們可以參考一下2016-06-06

