PyMongo/Mongoengine equivalent of mongodump

前端 未结 2 1054
佛祖请我去吃肉
佛祖请我去吃肉 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:10

    For my relatively small small database, I eventually used the following solution. It's not really suitable for big or complex databases, but it suffices for my case. It dumps all documents as a json to the backup directory. It's clunky, but it does not rely on other stuff than pymongo.

    from os.path import join
    import pymongo
    from bson.json_utils import dumps
    
    def backup_db(backup_db_dir):
        client = pymongo.MongoClient(host=, port=)
        database = client[]
        authenticated = database.authenticate(,)
        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))
    

提交回复
热议问题