Read and Write Files From MongoDB With Python

How to read and write files from MongoDB with Python.

  1. Install the following packages:

    import pandas as pd
    from pymongo import MongoClient
    import os
  2. Connect to MongoDB by running the following lines of code:

    # ====== Connection to MongoDB ====== #
    # To connect to MongoDB.
    client_mongo = MongoClient(os.environ['IP_MONGO'], int(os.environ['PORT_MONGO']))
    
    # To connect to the database.
    db = client_mongo.sandbox
    
    # To authenticate to the database.
    db.authenticate(os.environ['MONGO_USER'], os.environ['MONGO_PASSWORD'])
    
    # To connect to the collection.
    collection = db.helloworld
    The default port is 27017.
  3. You can now insert and query documents in MongoDB by running the following lines of code:

    • Insert Documents in MongoDB

    • Query Documents From MongoDB

    # ====== Inserting Documents ====== #
    # To create a simple pandas DataFrame.
    liste_hello = ['hello1','hello2']
    liste_world = ['world1','world2']
    df = pd.DataFrame(data = {'hello' : liste_hello, 'world': liste_world})
    
    # Bulk insertion of documents. Each row in the DataFrame will be a document in Mongo.
    collection.insert_many(df.to_dict('records'))
    # ====== Finding Documents ====== #
    documents = collection.find({'message': 'helloworld1'})
    df = pd.DataFrame(list(documents))