Featured Article

Read MongoDB Collection in PySpark Like a Pro

Kenneth Jul 13, 2026

When working with big data, it's crucial to leverage powerful tools like Apache Spark and MongoDB. But how do you harness the strengths of both? In this guide, we'll explore how to read a MongoDB collection in PySpark, combining the speed of Spark with the flexibility of MongoDB.

| Pythonista Planet
| Pythonista Planet

First, let's understand why you might want to do this. MongoDB excels in storing and working with semi-structured data, while Apache Spark shines in processing large datasets efficiently. By reading a MongoDB collection in PySpark, you can perform advanced transformations and analytics on your MongoDB data.

MongoDB Aggregation Pipeline — Visual Cheat Sheet for Developers
MongoDB Aggregation Pipeline — Visual Cheat Sheet for Developers

Setting Up the Environment

Before we dive into the code, ensure you have the required dependencies. You'll need to have both MongoDB and Spark installed, along with PyMongo and PySpark pandas.

Python Django MongoDB CRUD Tutorial (CREATE , READ , UPDATE , DELETE)
Python Django MongoDB CRUD Tutorial (CREATE , READ , UPDATE , DELETE)

You can install them using pip:

pip install pymongo pandas

many different books are arranged in the shape of a pyramid
many different books are arranged in the shape of a pyramid

Connecting to MongoDB with PySpark

First, use the PyMongo library to connect to your MongoDB instance from PySpark.

```python from py4j.java_gateway import java_import from pyspark.sql import SparkSession from pymongo import MongoClient # Initialize SparkSession spark = SparkSession.builder.appName('MongoDB with PySpark').getOrCreate() # Connect to MongoDB client = MongoClient('localhost', 27017) db = client['your_database'] # Replace with your database name ```

MongoDB Fundamentals | A Beginner's Guide to Basic Commands
MongoDB Fundamentals | A Beginner's Guide to Basic Commands

Reading MongoDB Data in DataFrame

PySpark provides the read.json method, which can also read data from MongoDB since MongoDB stores data in JSON-like format. Here's how you can read a collection:

```python df = spark.read.format('com.mongodb.spark.sql.DefaultSource') \ .option('database', 'your_database') \ .option('collection', 'collection_name') \ .load() ```

MongoDB Practice Tests for Beginners to Experts | NoSQL Quiz, MCQs & Interview Preparation (2026)
MongoDB Practice Tests for Beginners to Experts | NoSQL Quiz, MCQs & Interview Preparation (2026)

Note: You need to have the MongoDBspark package added to your classpath. If using maven, add the following to your pom.xml:

<dependency> <groupId>org.mongodb.spark</groupId> <artifactId>mongo-spark-connector_2.12</artifactId> <version>3.0.1</version> </dependency>

📚
📚
a stack of books sitting on top of a wooden table
a stack of books sitting on top of a wooden table
a book shelf filled with lots of books on top of white shelves in a room
a book shelf filled with lots of books on top of white shelves in a room
many books are stacked on top of each other in the shape of a rectangle
many books are stacked on top of each other in the shape of a rectangle
How to Run MongoDB in a Docker Container
How to Run MongoDB in a Docker Container
MongoDB Skillset Learning for Students from Youth Buddy
MongoDB Skillset Learning for Students from Youth Buddy
MongoDB Tutorial
MongoDB Tutorial
How To Create and Use Python Modules?
How To Create and Use Python Modules?
a stack of books sitting on top of a table
a stack of books sitting on top of a table

Performing Operations on MongoDB Data Using PySpark

Now that you have your MongoDB data in a PySpark DataFrame, you can perform various operations like transformations, aggregations, and actions.

```python # Count the number of documents df.count() # Show the first 5 rows df.show(5) # Perform operations like filter, groupBy, etc. df.filter(df.column == 'value').groupBy('column').count().show() ```

Writing DataFrame Back to MongoDB

Once you've performed your operations, you might want to write the transformed data back to MongoDB.

```python df.write.format('com.mongodb.spark.sql.DefaultSource') \ .option('database', 'your_database') \ .option('collection', 'output_collection_name') \ .mode('overwrite') \ .save() ```

Reading a MongoDB collection in PySpark opens up a world of possibilities for data processing and analysis. So, why wait? Explore these powerful tools and unlock the full potential of your data today!