codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🐍

Python Programming

50 / 68 topics
49Python MySQL (Create, Insert, Select, Update, Delete)50Python MongoDB (Insert, Find, Update, Delete)
Tutorials/Python Programming/Python MongoDB (Insert, Find, Update, Delete)
🐍Python Programming

Python MongoDB (Insert, Find, Update, Delete)

Updated 2026-04-20
3 min read

Python MongoDB (Insert, Find, Update, Delete)

MongoDB is a popular NoSQL database that stores data in JSON-like documents. This tutorial will guide you through the basics of interacting with MongoDB using Python, covering operations such as inserting, finding, updating, and deleting documents.

Prerequisites

Before we begin, ensure you have the following installed:

  • Python: Make sure you have Python 3.x installed on your system.
  • MongoDB: Install MongoDB Community Edition from mongodb.com.
  • PyMongo: This is the official Python driver for MongoDB. You can install it using pip:
    pip install pymongo
    

Connecting to MongoDB

To interact with MongoDB, you need to establish a connection. Here’s how you can do it:

from pymongo import MongoClient

# Connect to the MongoDB server running on localhost at port 27017
client = MongoClient('mongodb://localhost:27017/')

# Access the database named 'mydatabase'
db = client['mydatabase']

# Access the collection named 'mycollection'
collection = db['mycollection']

Explanation

  • MongoClient: This is used to create a connection to the MongoDB server.
  • Database and Collection: In MongoDB, data is organized into databases and collections. A database can contain multiple collections.

Inserting Documents

You can insert documents into a collection using the insert_one or insert_many methods.

Inserting a Single Document

# Define a document to be inserted
document = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

# Insert the document into the collection
result = collection.insert_one(document)

# Print the inserted document's ID
print(f"Inserted document with ID: {result.inserted_id}")

Explanation

  • insert_one: Inserts a single document into the collection.
  • inserted_id: Returns the unique identifier of the inserted document.

Inserting Multiple Documents

# Define multiple documents to be inserted
documents = [
    {"name": "Bob", "age": 25, "city": "Los Angeles"},
    {"name": "Charlie", "age": 35, "city": "Chicago"}
]

# Insert the documents into the collection
result = collection.insert_many(documents)

# Print the inserted document IDs
print(f"Inserted documents with IDs: {result.inserted_ids}")

Explanation

  • insert_many: Inserts multiple documents into the collection.
  • inserted_ids: Returns a list of unique identifiers for the inserted documents.

Finding Documents

You can retrieve documents from a collection using various query methods.

Finding a Single Document

# Find a single document where 'name' is 'Alice'
document = collection.find_one({"name": "Alice"})

# Print the found document
print(document)

Explanation

  • find_one: Returns the first document that matches the specified filter.

Finding Multiple Documents

# Find all documents where 'age' is greater than 25
documents = collection.find({"age": {"$gt": 25}})

# Print each found document
for doc in documents:
    print(doc)

Explanation

  • find: Returns a cursor to the documents that match the specified filter.
  • $gt: A query operator that matches values greater than the specified value.

Updating Documents

You can update documents using the update_one or update_many methods.

Updating a Single Document

# Update the 'age' of the document where 'name' is 'Alice'
result = collection.update_one({"name": "Alice"}, {"$set": {"age": 31}})

# Print the number of documents modified
print(f"Modified count: {result.modified_count}")

Explanation

  • update_one: Updates a single document that matches the specified filter.
  • $set: An update operator that replaces the value of a field.

Updating Multiple Documents

# Update the 'city' of all documents where 'age' is greater than 25
result = collection.update_many({"age": {"$gt": 25}}, {"$set": {"city": "San Francisco"}})

# Print the number of documents modified
print(f"Modified count: {result.modified_count}")

Explanation

  • update_many: Updates all documents that match the specified filter.

Deleting Documents

You can delete documents using the delete_one or delete_many methods.

Deleting a Single Document

# Delete the document where 'name' is 'Bob'
result = collection.delete_one({"name": "Bob"})

# Print the number of documents deleted
print(f"Deleted count: {result.deleted_count}")

Explanation

  • delete_one: Deletes a single document that matches the specified filter.

Deleting Multiple Documents

# Delete all documents where 'age' is greater than 30
result = collection.delete_many({"age": {"$gt": 30}})

# Print the number of documents deleted
print(f"Deleted count: {result.deleted_count}")

Explanation

  • delete_many: Deletes all documents that match the specified filter.

Best Practices

  1. Error Handling: Always handle exceptions when interacting with databases to ensure your application remains robust.
  2. Connection Management: Close database connections when they are no longer needed to free up resources.
  3. Indexing: Use indexes on frequently queried fields to improve performance.
  4. Security: Ensure that your MongoDB server is secured, especially if it's exposed to the internet.

Conclusion

This tutorial has covered the basics of interacting with MongoDB using Python, including inserting, finding, updating, and deleting documents. By following these steps and best practices, you can effectively manage data in MongoDB using Python.

Feel free to explore more advanced features of PyMongo and MongoDB to enhance your applications.


PreviousPython MySQL (Create, Insert, Select, Update, Delete)Next NumPy Tutorial

Recommended Gear

Python MySQL (Create, Insert, Select, Update, Delete)NumPy Tutorial