Skip to content

Instantly share code, notes, and snippets.

@Denilson-Semedo
Created November 30, 2023 06:01
Show Gist options
  • Save Denilson-Semedo/efa84f652c53ae6104dab3057f460a82 to your computer and use it in GitHub Desktop.
Save Denilson-Semedo/efa84f652c53ae6104dab3057f460a82 to your computer and use it in GitHub Desktop.
MongoDB Cheatsheet

MongoDB Cheatsheet

Introduction to MongoDB

Welcome to the MongoDB Cheatsheet – A short and comprehensive guide to MongoDB, the NoSQL database renowned for its flexibility, scalability, and high performance. This cheatsheet is designed to help with the MongoDB implementation in Pyhton.

For more in-depth information and detailed documentation, visit the official MongoDB documentation https://www.mongodb.com/docs/
Here you can access a MongoDB CRUD operations tutorial with Python(Fastapi) https://www.mongodb.com/languages/python/pymongo-tutorial

Key Concepts

  • Document: Basic unit of data in MongoDB, similar to a row in relational databases.
  • Collection: Group of MongoDB documents. Equivalent to a table in relational databases.
  • Database: Container for collections.

Getting Started with MongoDB Atlas

MongoDB Atlas is a cloud-based database service that simplifies database management and scaling.

Steps to Get Started

  1. Create an Account: Sign up for MongoDB Atlas at https://www.mongodb.com/cloud/atlas.

  2. Create a Cluster: Set up a MongoDB cluster to host your database.

  3. Connect to Cluster: Obtain connection string and connect to your cluster.

MongoDB and the Document Model

MongoDB uses a flexible, schema-less document model.

Document Structure

A MongoDB document is a JSON-like BSON (Binary JSON) object. Example:

{
  "_id": ObjectId("5f5b2f9a81b24f24d7e9379a"),
  "name": "John Doe",
  "age": 30,
  "email": "john@example.com"
}

Connecting to a MongoDB Database

Connection in Python

Use PyMongo to connect to MongoDB in Python:

from pymongo import MongoClient

# Connect to MongoDB
client = MongoClient("mongodb://username:password@host:port/database")

CRUD Operations

Insert and Find Documents

# Insert Document
result = db.collection.insert_one({"name": "Alice", "age": 25})

# Find Document
document = db.collection.find_one({"name": "Alice"})

Replace and Delete Documents

# Replace Document
result = db.collection.replace_one({"name": "Alice"}, {"name": "Alice", "age": 26})

# Delete Document
result = db.collection.delete_one({"name": "Alice"})

Modifying Query Results

# Update Document
result = db.collection.update_one({"name": "Alice"}, {"$set": {"age": 27}})

CRUD Operations in Python

# PyMongo Example
from pymongo import MongoClient

client = MongoClient("mongodb://username:password@host:port/database")
db = client.mydatabase
collection = db.mycollection

# Perform CRUD operations

# Single Operation Example
result = collection.insert_one({"name": "Alice", "age": 25})
document = collection.find_one({"name": "Alice"})
result = collection.replace_one({"name": "Alice"}, {"name": "Alice", "age": 26})
result = collection.delete_one({"name": "Alice"})

# Multiple Operation Example
result = collection.insert_many([{"name": "Alice", "age": 25}, {"name": "Bob", "age": 27}])
documents = collection.find({"age": {"$gte": 25}})
result = collection.update_many({"age": {"$gte": 25}}, {"$set": {"age": 26}})
result = collection.delete_many({"age": {"$gte": 25}})

MongoDB Aggregation

MongoDB Aggregation Pipeline allows the processing of data documents to return computed results.

Aggregation Stages

  • $match: Filters the documents.
  • $group: Groups documents based on certain criteria.
  • $project: Reshapes the documents.
  • $sort: Sorts all input documents.

MongoDB Aggregation in Python

# Aggregation Pipeline Example
pipeline = [
    {"$match": {"age": {"$gte": 25}}},
    {"$group": {"_id": "$age", "count": {"$sum": 1}}},
    {"$project": {"_id": 0, "age": "$_id", "count": 1}}
]

result = db.collection.aggregate(pipeline)

MongoDB Indexes

Indexes in MongoDB improve the performance of queries.

Creating Index

# Create Index
db.collection.create_index([("name", 1)])

MongoDB Atlas Search

MongoDB Atlas Search enables full-text search capabilities.

Creating Text Index

# Create Text Index
db.collection.create_index([("content", "text")])

MongoDB Transactions

MongoDB supports multi-document transactions.

Transaction Example

# Start Transaction
with client.start_session() as session:
    with session.start_transaction():
        db.collection1.update_one({"_id": 1}, {"$set": {"field1": "value1"}})
        db.collection2.delete_one({"_id": 2})

MongoDB Compass

MongoDB Compass is a graphical user interface for MongoDB.

Features

  • Visualize your schema.
  • Explore and interact with your data.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment