/
Python - Insert and Query documents in MongoDB with Security
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))
, multiple selections available,
Related content
Python - Read & Write tables from MySQL with Security
Python - Read & Write tables from MySQL with Security
More like this
Python - Read & Write tables from PostgreSQL with Security
Python - Read & Write tables from PostgreSQL with Security
More like this
Python - Index & Search documents in ElasticSearch
Python - Index & Search documents in ElasticSearch
More like this
Java - Read & Write files from MongoDB with security
Java - Read & Write files from MongoDB with security
More like this
R - Read & Write files from MongoDB with security
R - Read & Write files from MongoDB with security
More like this
Python - Read & Write files from Hive with Security
Python - Read & Write files from Hive with Security
More like this