PyMongo/Mongoengine equivalent of mongodump

前端 未结 2 1051
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-11 17:36

Is there an equivalent function in PyMongo or mongoengine to MongoDB\'s mongodump? I can\'t seem to find anything in the docs.

<
2条回答
  •  走了就别回头了
    2021-01-11 18:15

    The accepted answer is not working anymore. Here is a revised code:

    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[]
        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('.')
    

提交回复
热议问题