问题描述
无论如何,当您使用 shell 时,转储和恢复 mongo db 似乎相当简单:您只需使用命令 mongorestore
和 mongodump
。但如果我没记错的话,这些命令要求你离开你的活动 mongo shell。
此外,在用 Python 或 Prolog 编写时,我有不同的方式与 mongo 进行通信。我可以使用 PyMonogo,或者就我而言,我通过 RosProlog 进行通信。两者都可以执行 mongo shell 命令,但我想不出一种方法来执行类似于 sparkSession.sql("WITH dups AS (
SELECT *,ROW_NUMBER() OVER (PARTITION BY name ORDER BY flag DESC) AS rn
FROM (
SELECT name,flag,CONCAT_WS(',',COLLECT_SET(code) OVER (PARTITION BY name)) AS code FROM tmp_table)
) SELECT name,flag AS hasYFlag,IF(flag='Y',code,null) AS codeList FROM dups WHERE rn = 1")
和 mongorestore
的东西。
当然我可以在 Python 中使用 mongodump
(或在 prolog 中使用 os.system()
)来执行 shell 命令,但它看起来很丑陋,我想避免它。我也可以自己写一个 .bson-parser 但这真的有必要吗? mongo shell 中真的没有等价物吗?
解决方法
mongodump 和 mongorestore 是用 golang https://github.com/mongodb/mongo-tools 编写的操作系统级实用程序。您确实需要在 mongo shell 之外运行它们。
推荐的方法是使用标准的 mongodump 和 mongorestore 作为子进程,但没有魔法,你可以在 Python 中做同样的事情。
来自https://jira.mongodb.org/browse/PYTHON-664:
from bson import BSON,decode_all
from pymongo import MongoClient
client = MongoClient()
source_collection = client.db.collection
# Dump.
with open('file.bson','wb+') as f:
for doc in source_collection.find():
f.write(BSON.encode(doc))
# Restore.
target_collection = client.db.collection2
with open('file.bson','rb') as f:
target_collection.insert(decode_all(f.read()))
它不会那么高效,备份将与标准备份不兼容,并且您可能会在不转储 oplog 的情况下错过一些边缘情况。
,这个python解决方案适用于windows和linux;确定它有点hacky但几乎不难看。
import subprocess
output = subprocess.run(['mongodump','--uri','mongodb://localhost','--readPreference','primary'],capture_output=True)
print(output)
添加您需要的任何其他参数,例如f'--archive={my_file}'