文章詳情頁
MySQL實現(xiàn)批量推送數(shù)據(jù)到Mongo
瀏覽:201日期:2023-05-05 10:11:54
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)文章希望大家以后多多支持!
標(biāo)簽:
MySQL
排行榜
