ProCodebaseProCodebase
  • ModusA Growth OS for your business, on WhatsAppKiosqSell more. Chase less.AI InterviewerAutomated screening & AI-led interviewsXperto AIAI prep companion for candidatesAI Tools HubResume builder, learning paths & more
  • Pre-Vetted DevelopersScreened, scored and ready to interviewAI-Native DevelopersSenior engineers on an hourly basis
  • Services
  • Features
  • Jobs
  • FAQs
Sign inBook a demo
  • Services
  • Features
  • Jobs
  • FAQs
Sign inBook a demo
ProCodebaseProCodebase

ProCodebase Technologies builds AI products for hiring and growth, and ships software for clients as a technical consultancy. We source, screen and deliver pre-vetted developers — so you only interview high-signal candidates.

Products

  • Modus
  • Kiosq
  • AI Interviewer
  • Xperto AI
  • AI Tools Hub

Hire & build

  • Pre-Vetted Developers
  • AI-Native Developers
  • Technical Consultancy
  • MVP Development
  • Features

Resources

  • Articles
  • Topics
  • Certifications
  • Collections
  • Jobs

Company

  • About Us
  • Contact Us
  • Book a Demo
  • FAQs

© 2026 ProCodebase Technologies. All rights reserved.

  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation

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

  • Advanced Python Mastery: Techniques for Experts

    15/01/2025 · Python

  • Mastering LangGraph: Stateful, Orchestration Framework

    17/11/2024 · Python

  • Python Basics: Comprehensive Guide

    21/09/2024 · Python

  • Seaborn: Data Visualization from Basics to Advanced

    06/10/2024 · Python

  • Mastering NLTK for Natural Language Processing

    22/11/2024 · Python

Related articles

  • Setting Up Your Python Environment for Automating Everything

    08/12/2024 · Python

  • Understanding Loops in Python

    21/09/2024 · Python

  • Delving into Python Internals

    13/01/2025 · Python

  • Understanding Lambda Functions and Anonymous Functions in Python

    21/09/2024 · Python

  • Indexing and Optimizing Queries in MongoDB with Python

    08/11/2024 · Python

  • Real World Automation Projects with Python

    08/12/2024 · Python

  • Understanding Python Functions and Scope

    21/09/2024 · Python

Popular category

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