Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 2 Next »

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 simple documents and putting them in a list
liste_docs=[{'message': 'helloworld1'},{'message': 'helloworld2'}]
# Bulk inserting documents
collection.insert_many(liste_docs)

How to query a document from Mongo with Python ?

Code example

# ====== Finding Documents ====== #
documents = collection.find({'message': 'helloworld1'})
  • No labels