pythonjsonmongodbpymongo-3.x

How to dump a collection to json file using pymongo


I am trying to dump a collection to .json file but after looking in pymongo tutorial I can not find any thing that relates to it.

Tutorial link: https://api.mongodb.com/python/current/tutorial.html


Solution

  • Just get all documents and save them to file e.g.:

    from bson.json_util import dumps
    from pymongo import MongoClient
    
    if __name__ == '__main__':
        client = MongoClient()
        db = client.db_name
        collection = db.collection_name
        cursor = collection.find({})
        with open('collection.json', 'w') as file:
            file.write('[')
            for document in cursor:
                file.write(dumps(document))
                file.write(',')
            file.write(']')