PYTHON Tutorial

Connecting to MongoDB

Key Concepts

  • PyMongo: A popular Python library for interacting with MongoDB.
  • MongoEngine: An Object-Document Mapper (ODM) for Python that provides a convenient way to map Python classes to MongoDB documents.

Connecting to MongoDB

Using PyMongo:
  • Install PyMongo: pip install pymongo
  • Create a client connection:
    from pymongo import MongoClient
    
    client = MongoClient("mongodb://username:password@host:port")
    
  • Access a database and collection:
    db = client["mydb"]
    collection = db["mycollection"]
    
Using MongoEngine:
  • Install MongoEngine: pip install mongoengine
  • Connect to MongoDB:
    from mongoengine import connect
    
    connect("mongodb://username:password@host:port", alias="default")
    
  • Define a model class:
    class Person(Document):
        name = StringField()
        age = IntField()
    
    This will create a Person collection in MongoDB.

Methods and Libraries

Method Library
Find documents find(), find_one()
Insert documents insert_one(), insert_many()
Update documents update_one(), update_many()
Delete documents delete_one(), delete_many()

Python Example

from pymongo import MongoClient

client = MongoClient("mongodb://localhost:27017")
db = client["mydb"]
collection = db["mycollection"]

# Insert a document
collection.insert_one({"name": "John Doe", "age": 30})

# Find a document
document = collection.find_one({"name": "John Doe"})

# Print the document
print(document)