Skip to main content

MongoDB with Python

Welcome to this tutorial on MongoDB with Python. As a NoSQL database, MongoDB offers flexibility in working with data, making it a popular choice for many developers. In this tutorial, we will cover how you can use Python, a popular and beginner-friendly language, to interact with MongoDB. Let's dive in!

Prerequisites

Before we get started, ensure that you have Python and MongoDB installed on your machine. If you haven't already installed them, follow the official guides:

Once installed, we need to install the pymongo driver which allows Python to communicate with MongoDB. You can install it using pip:

pip install pymongo

Connecting Python to MongoDB

To interact with MongoDB in Python, you first need to import pymongo and establish a connection to your MongoDB server.

from pymongo import MongoClient

client = MongoClient('mongodb://localhost:27017/')

Working with Databases

To work with a MongoDB database, you can access it as an attribute of the client object. If the database doesn't exist, MongoDB will create it for you.

db = client.my_database

Collections and Documents

In MongoDB, data are stored in collections, which are similar to tables in a relational database. Each document in a collection is similar to a row in a table.

To create a collection:

my_collection = db.my_collection

To insert a document:

document = {"name": "John", "age": 30, "city": "New York"}

my_collection.insert_one(document)

You can also insert multiple documents at once:

documents = [
{"name": "John", "age": 30, "city": "New York"},
{"name": "Jane", "age": 28, "city": "Chicago"},
]

my_collection.insert_many(documents)

Querying Documents

You can query documents in a collection using the find method:

query_result = my_collection.find({"age": 30})

You can also query for multiple conditions:

query_result = my_collection.find({"age": 30, "city": "New York"})

Updating Documents

To update a document, you can use the update_one or update_many methods:

my_collection.update_one(
{"name": "John"},
{"$set": {"age": 31}}
)

Deleting Documents

To delete a document, you can use the delete_one or delete_many methods:

my_collection.delete_one({"name": "John"})

Conclusion

In this tutorial, you have learned how to interact with MongoDB using Python. We covered how to connect to MongoDB, create databases and collections, insert, query, update, and delete documents. Remember, practice is key when learning a new language or technology, so try to implement what you have learned in a practical project. Happy coding!