Python - Insert and Query documents in MongoDB with Security

Gist Page : example-python-read-and-write-from-mongo

Common part

Libraries dependency

import pandas as pd
from pymongo import MongoClient
import os

Mongo Connection

Default port is 27017

Connection

# ====== Connection ====== #
# Connection to Mongo
client_mongo = MongoClient(os.environ['IP_MONGO'],27017)
# Connection to the database
db = client_mongo.sandbox
# Authenticating to the database
db.authenticate(os.environ['MONGO_USER'],os.environ['MONGO_PASSWORD'])
# Connection to the collection
collection = db.helloworld

How to insert a document in Mongo with Python ?

Code example

# ====== Inserting Documents ====== #
# Creating a simple Pandas DataFrame
liste_hello = ['hello1','hello2']
liste_world = ['world1','world2']
df = pd.DataFrame(data = {'hello' : liste_hello, 'world': liste_world})
# Bulk inserting documents. Each row in the DataFrame will be a document in Mongo
db.insert_many(df.to_dict('records'))

How to query a document from Mongo with Python ?

Code example

# ====== Finding Documents ====== #
documents = collection.find({'message': 'helloworld1'})
df = pd.DataFrame(list(documents))