Featured Article

Effortless PySpark to MongoDB Write Operations Tutorial

Kenneth Jul 13, 2026

Integrating Apache Spark with MongoDB can greatly enhance data processing capabilities, allowing for real-time data analysis and storage. Python, with its library Pyspark, provides a seamless way to connect these two powerful tools. Here, we'll guide you through writing to MongoDB using Pyspark.

| Pythonista Planet
| Pythonista Planet

Before delving into the specifics, ensure you have the required dependencies. In your Pyspark shell or script, import the necessary libraries:

MongoDB find in Python cheat-sheet
MongoDB find in Python cheat-sheet

Setting Up the Connection

Establishing a connection to MongoDB involves using the MongoSpark connector, which enables data exchange between Spark and MongoDB.

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

Firstly, add the MongoSpark connector to your project by including the following dependencies in your build file:

```xml org.mongodb.spark spark-mongo_2.11 3.0.1 ```

Creating a SparkContext

MongoDB Tutorial
MongoDB Tutorial

After setting up the dependency, create a SparkContext and specify MongoDB as the data source:

```python from pyspark import SparkContext sc = SparkContext() df = sc.textFile("mongodb://localhost:27017/mydb.mydbcollection").toDF("column_name") ```

Replace "localhost:27017" with your MongoDB URI and "mydb.mydbcollection" with your database and collection name.

Reading Data from MongoDB

Post by @im-a-developer · 1 image
Post by @im-a-developer · 1 image

Once the connection is established, you can read data from MongoDB as a DataFrame using the `load` method provided by the MongoSpark connector:

```python from org.apache.spark.sql import SparkSession spark = SparkSession.builder \ .appName("Pyspark MongoDB") \ .config("spark.mongodb.input.uri", "mongodb://localhost:27017/mydb.mydbcollection") \ .getOrCreate() df = spark.read.format("com.mongodb.spark.sql default").load() ```

You can also specify the MongoDB URI in the `read` method as follows:

DataFrame `df` is now ready for transformations and actions, just like any other DataFrame in Spark.

MongoDB Skillset Learning for Students from Youth Buddy
MongoDB Skillset Learning for Students from Youth Buddy

Writing to MongoDB

Writing data to MongoDB is as straightforward as reading. The MongoSpark connector provides the `write` method for this purpose.

Using React Send Form Data to MongoDB Database | POST API in Nodejs  || MERN Stack || Restful APIs
Using React Send Form Data to MongoDB Database | POST API in Nodejs || MERN Stack || Restful APIs
PyTorch Machine Learning Framework Compromised with Malicious Dependency
PyTorch Machine Learning Framework Compromised with Malicious Dependency
IngramSpark Self-Publishing: Process, Royalties, Review, & Advice
IngramSpark Self-Publishing: Process, Royalties, Review, & Advice
How to Make Money Writing
How to Make Money Writing
the poster for writing international monologue
the poster for writing international monologue
the words are written in black and white, with an image of a person's head
the words are written in black and white, with an image of a person's head
Master MkDocs for Plotly Dash Apps
Master MkDocs for Plotly Dash Apps
Georgian Language Script, Cursive Cursive Georgian Alphabet, Georgian Script Alphabet, Georgian Language Script Example, Armenian Cursive, Georgian Cursive, Georgian Scripts, Georgian Cursive Writing, Georgian Script Translation
Georgian Language Script, Cursive Cursive Georgian Alphabet, Georgian Script Alphabet, Georgian Language Script Example, Armenian Cursive, Georgian Cursive, Georgian Scripts, Georgian Cursive Writing, Georgian Script Translation
How to make money through Medium
How to make money through Medium

Before writing, ensure that your DataFrame `df` is in the required format. You can perform necessary transformations like `select`, `filter`, `groupBy`, etc., as needed.

Writing a DataFrame to MongoDB

Use the `write` method to write a DataFrame to MongoDB. Specify the MongoDB URI and collection name:

```python df.write.format("com.mongodb.spark.sql") \ .mode('overwrite') \ .option("spark.mongodb.output.uri", "mongodb://localhost:27017/mydb.mydbcollection") \ .save() ```

Replace "localhost:27017" and "mydb.mydbcollection" with your MongoDB URI and the desired collection name.

Writing a Dataset to MongoDB

If you're working with Datasets instead of DataFrames, use the `write` method as follows:

```python ds.write.format("com.mongodb.spark.sql") \ .mode('overwrite') \ .option("spark.mongodb.output.uri", "mongodb://localhost:27017/mydb.mydbcollection") \ .save() ```

Remember to replace the MongoDB URI and collection name as needed.

By following these steps, you can now efficiently write data from Pyspark to MongoDB, enabling real-time data processing and analysis.

Now that you have a solid foundation in writing data to MongoDB using Pyspark, explore more advanced use cases, such as upserting documents, managing batch sizes, and tuning performance to suit your specific data processing needs.