Introduction to MongoDB
MongoDB is a NoSQL database designed for scalability and performance. Unlike traditional SQL databases, it uses a flexible schema that allows for the storage of documents in a format similar to JSON (JavaScript Object Notation). This makes MongoDB an excellent choice for applications where data structures may evolve over time.
Prerequisites
Before we begin, ensure you have the following:
-
Python: Ensure Python 3.x is installed on your machine. You can download it from python.org.
-
MongoDB: You need a MongoDB server running locally or access to a MongoDB instance in the cloud. For local installation, head to the MongoDB installation guide appropriate for your operating system.
-
PyMongo: This is the official MongoDB driver for Python. You can install PyMongo using pip.
pip install pymongo
Step 1: Starting the MongoDB Server
If you have installed MongoDB locally, you can start the server using the following command in your terminal:
mongod
This command will run the MongoDB server and listen on the default port 27017
. You should see output indicating that the server is running.
Step 2: Verify MongoDB Installation
To check whether MongoDB is running, you can use the MongoDB shell tool by typing:
mongo
If the installation is successful, you will see output similar to this, indicating that you are connected to your MongoDB instance:
MongoDB shell version vX.Y.Z
connecting to: mongodb://127.0.0.1:27017
Step 3: Connecting to MongoDB using PyMongo
Now that your MongoDB server is running, let's connect to it through Python using PyMongo.
Sample Python Script
You can create a Python script named connect_mongo.py
with the following content:
import pymongo # Connection to MongoDB client = pymongo.MongoClient("mongodb://localhost:27017/") # Creating or connecting to a database db = client["my_database"] # Creating or connecting to a collection collection = db["my_collection"] # Inserting a sample document sample_document = { "name": "John Doe", "age": 30, "city": "New York" } # Insert document into the collection collection.insert_one(sample_document) print("Document inserted successfully!")
Explanation
-
Importing PyMongo: You start by importing the
pymongo
library. -
Creating a MongoClient: The
MongoClient
object creates a connection to the MongoDB server. Here we connect to the defaultlocalhost
and port27017
. -
Database and Collection: A database is created if it doesn’t exist. Here,
my_database
is referenced, as well as a collection namedmy_collection
. -
Inserting Documents: This script inserts a simple document into the collection and prints a confirmation message. The
insert_one
method is used for single document insertion.
Running the Script
To run your script, execute the following command in your terminal:
python connect_mongo.py
If everything goes well, you should see the message:
Document inserted successfully!
Step 4: Querying the Database
Next, let's retrieve the document we just inserted. Update your script and add the following code after the insert operation:
# Querying the collection query_result = collection.find_one({"name": "John Doe"}) if query_result: print("Document found:", query_result) else: print("No document matches the provided query.")
Explanation
-
Querying the Collection: The
find_one
method fetches a single document that matches the specified query — in this case, where the name is "John Doe". -
Printing Results: If a document is found, it is printed; otherwise, a message indicates no matches.
Re-run your script, and you should see output that resembles:
Document found: {'_id': ObjectId('...'), 'name': 'John Doe', 'age': 30, 'city': 'New York'}
Conclusion
Now you have successfully set up MongoDB and connected it with Python using PyMongo! You've learned how to start your MongoDB server, connect using Python, insert a document, and query data. This foundational knowledge sets the stage for exploring more complex operations and building dynamic applications with Python and MongoDB.