logologo
  • Dashboard
  • Features
  • AI Tools
  • FAQs
  • Jobs
  • Modus
logologo

We source, screen & deliver pre-vetted developers—so you only interview high-signal candidates matched to your criteria.

Useful Links

  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation
  • About Us

Resources

  • Certifications
  • Topics
  • Collections
  • Articles
  • Services

AI Tools

  • AI Interviewer
  • Xperto AI
  • Pre-Vetted Top Developers

Procodebase © 2025. All rights reserved.

Level Up Your Skills with Xperto-AI

A multi-AI agent platform that helps you level up your development skills and ace your interview preparation to secure your dream job.

Launch Xperto-AI

CRUD Operations in MongoDB with Python

author
Generated by
ProCodebase AI

08/11/2024

Python

Sign in to read full article

MongoDB is a popular NoSQL database that stores data in a flexible, JSON-like format called BSON (Binary JSON). It is particularly well-suited for handling large volumes of unstructured data. When working with MongoDB and Python, you'll find the pymongo library to be very useful as it provides a straightforward way to interact with your MongoDB database.

In this blog, we’ll break down the basic CRUD operations that you can perform with Python and MongoDB.

Setting Up Your Environment

Prerequisites

To follow along, you'll need to have Python and MongoDB installed on your system. Also, ensure you have the pymongo library installed. You can install it via pip:

pip install pymongo

Connecting to MongoDB

First, let’s connect to our MongoDB instance. Here’s a simple piece of code that connects to the default MongoDB URI:

from pymongo import MongoClient # Connect to MongoDB client = MongoClient('mongodb://localhost:27017/') # Access the 'testdb' database db = client['testdb']

Creating Documents (C)

The first operation we’ll look at is creating documents. In MongoDB, documents are akin to rows in traditional SQL databases. Let's create a collection called users and insert some documents.

Inserting a Single Document

# Define a user document user = { "name": "Alice", "age": 30, "status": "active" } # Insert the document into the 'users' collection result = db.users.insert_one(user) print(f"Inserted document ID: {result.inserted_id}")

Inserting Multiple Documents

# Define multiple users users = [ {"name": "Bob", "age": 25, "status": "active"}, {"name": "Charlie", "age": 28, "status": "inactive"} ] # Insert multiple documents results = db.users.insert_many(users) print("Inserted document IDs:", results.inserted_ids)

Reading Documents (R)

After inserting documents, the next step is to read data from your database. There are several ways to query data in MongoDB.

Finding a Single Document

You can retrieve a single document based on a specific criterion:

# Find one document user = db.users.find_one({"name": "Alice"}) print(user)

Finding Multiple Documents

To retrieve multiple documents, you can use find():

# Find all active users active_users = db.users.find({"status": "active"}) print("Active Users:") for user in active_users: print(user)

Using Projection

Sometimes, you might only want to retrieve certain fields from the documents. You can achieve this with projection:

# Find names and ages of all users users_projection = db.users.find({}, {"name": 1, "age": 1}) for user in users_projection: print(user)

Updating Documents (U)

Updating documents in MongoDB is straightforward. Let's explore how to update existing records.

Updating a Single Document

# Update Alice's status update_result = db.users.update_one( {"name": "Alice"}, {"$set": {"status": "inactive"}} ) print(f"Modified count: {update_result.modified_count}")

Updating Multiple Documents

You can also update multiple documents with a single command:

# Set all active users to inactive update_results = db.users.update_many( {"status": "active"}, {"$set": {"status": "inactive"}} ) print(f"Modified count (multiple): {update_results.modified_count}")

Deleting Documents (D)

The last operation we'll cover is deleting documents. It’s essential to handle this carefully as it can lead to data loss if not done correctly.

Deleting a Single Document

# Delete a single document delete_result = db.users.delete_one({"name": "Charlie"}) print(f"Deleted count: {delete_result.deleted_count}")

Deleting Multiple Documents

To remove multiple documents based on a condition, you can use:

# Delete all inactive users delete_results = db.users.delete_many({"status": "inactive"}) print(f"Deleted count (multiple): {delete_results.deleted_count}")

Wrapping Up

You’ve now learned how to perform CRUD operations in MongoDB using Python. These operations form the backbone of database interaction and are crucial for any data-driven application. With these skills at your fingertips, you can start building robust applications using MongoDB and Python with confidence. Happy coding!

Popular Tags

PythonMongoDBCRUD operations

Share now!

Like & Bookmark!

Related Collections

  • LangChain Mastery: From Basics to Advanced

    26/10/2024 | Python

  • FastAPI Mastery: From Zero to Hero

    15/10/2024 | Python

  • Python Basics: Comprehensive Guide

    21/09/2024 | Python

  • LlamaIndex: Data Framework for LLM Apps

    05/11/2024 | Python

  • Advanced Python Mastery: Techniques for Experts

    15/01/2025 | Python

Related Articles

  • Advanced Python Automation Tools

    08/12/2024 | Python

  • Building Domain Specific Languages with Python

    13/01/2025 | Python

  • Diving into Virtual Environments and Package Management with pip

    21/09/2024 | Python

  • Training and Testing Models with NLTK

    22/11/2024 | Python

  • Installing and Setting Up Redis with Python

    08/11/2024 | Python

  • Understanding Loops in Python

    21/09/2024 | Python

  • Stemming with Porter and Lancaster Stemmer in Python

    22/11/2024 | Python

Popular Category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design