Gx1*_*TDa 7 python mongodb pymongo mongoengine
是否有相同功能PyMongo或mongoengine到MongoDB的mongodump?我似乎无法在文档中找到任何内容.
使用案例:我需要定期备份远程mongo数据库.本地机器是没有安装mongo的生产服务器,我没有管理员权限,所以我不能subprocess用来打电话mongodump.我可以在virtualenv上本地安装mongo客户端,但我更喜欢API调用.
非常感谢 :-).
Gx1*_*TDa 10
对于我相对较小的小型数据库,我最终使用了以下解决方案.它不适合大型或复杂的数据库,但它足以满足我的需求.它将所有文档作为json转储到备份目录.它很笨重,但它不依赖于其他东西而不是pymongo.
from os.path import join
import pymongo
from bson.json_utils import dumps
def backup_db(backup_db_dir):
client = pymongo.MongoClient(host=<host>, port=<port>)
database = client[<db_name>]
authenticated = database.authenticate(<uname>,<pwd>)
assert authenticated, "Could not authenticate to database!"
collections = database.collection_names()
for i, collection_name in enumerate(collections):
col = getattr(database,collections[i])
collection = col.find()
jsonpath = collection_name + ".json"
jsonpath = join(backup_db_dir, jsonpath)
with open(jsonpath, 'wb') as jsonfile:
jsonfile.write(dumps(collection))
Run Code Online (Sandbox Code Playgroud)
接受的答案不再有效。这是修改后的代码:
from os.path import join
import pymongo
from bson.json_util import dumps
def backup_db(backup_db_dir):
client = pymongo.MongoClient(host=..., port=..., username=..., password=...)
database = client[<db_name>]
collections = database.collection_names()
for i, collection_name in enumerate(collections):
col = getattr(database,collections[i])
collection = col.find()
jsonpath = collection_name + ".json"
jsonpath = join(backup_db_dir, jsonpath)
with open(jsonpath, 'wb') as jsonfile:
jsonfile.write(dumps(collection).encode())
backup_db('.')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6881 次 |
| 最近记录: |