Featured Article

Spark MongoDB Write Example: Master Real-Time Data Storage

Kenneth Jul 13, 2026

Accelerating data-driven applications has become a critical factor in today's competitive business landscape. One powerful combination for achieving this is using the Spark processing engine with MongoDB, a leading NoSQL database. This article explores how to write data from Spark to MongoDB, a practical use case that enables real-time data analysis and storage.

Free AI Content Detector & Humanizer: Analyze & Optimize Your Text
Free AI Content Detector & Humanizer: Analyze & Optimize Your Text

Spark and MongoDB unite the best of both worlds, leveraging Spark's speed and analytical prowess with MongoDB's flexibility and scalability. By integrating these two powerhouses, you can build agile data pipelines, streamline ETL processes, and unlock insights dissimilarly.

Introducing the Find the Write Spark Challenge
Introducing the Find the Write Spark Challenge

Setting Up the Connection

Before diving into writing data, ensure you have set up the connection between Spark and MongoDB. The MongoDB Spark Connector facilitates this integration, enabling seamless data exchange between the two ecosystems.

Few Shot Prompting Brand Voice Example AI 2026 Real Working
Few Shot Prompting Brand Voice Example AI 2026 Real Working

Add the following dependency to your Spark project to establish the connection:

<dependency>
  <groupId>org.mongodb</groupId>
  <artifactId>mongodb-spark-connector_2.4.0</artifactId>
  <version>10.0.0</artifactId>
</dependency>

Spark RDD to MongoDB

a screenshot of a web page with the text table that uses trigger when the trigger is execute
a screenshot of a web page with the text table that uses trigger when the trigger is execute

One way to write data from Spark to MongoDB involves using Resilient Distributed Datasets (RDDs). RDDs are perfect for batch processing and can be converted into DataFrames or Datasets for more extensive analysis if needed.

Here's a simple example of writing an RDD to MongoDB:

val sparkConf = new SparkConf().setMaster("local").setAppName("SparkMongoExample")
val sc = new SparkContext(sparkConf)

val rdd = sc.parallelize(Seq("Hello, MongoDB!", "Spark + MongoDB = Awesome!"))
rdd.saveToMongoDB("mongodb://localhost:27017/mydb.mycollection")

Spark DataFrame to MongoDB

⚔️ Fantasy Plot Generator for Writers (Free Story Idea Tool)
⚔️ Fantasy Plot Generator for Writers (Free Story Idea Tool)

DataFrames are a more structured and optimized data abstraction in Spark, ideal for transforming and querying data. They can easily be written to MongoDB using the MongoDB Spark Connector.

Let's create a DataFrame and write it to MongoDB:

import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.functions._

val spark = SparkSession.builder.appName("SparkMongoDataFrame").getOrCreate()

val df = Seq("Alice", "Bob", 25, 30).toDF("Name", "Age")
df.write.format("com.mongodb.spark.sql.DefaultSource").option("database", "mydb").option("collection", "mycollection").mode("overwrite").save()

Writing to MongoDB using Datasets

Random Writing Prompt Generator – Free Online Creative Writing Tool
Random Writing Prompt Generator – Free Online Creative Writing Tool

Datasets provide the benefits of RDDs along with the convenience of DataFrames. They offer improved performance and integration with other Spark libraries. Writing Datasets to MongoDB is quite straightforward using the connector.

Here's an example of writing a Dataset to MongoDB:

Proven Methods To Write Captions That Spark Conversations
Proven Methods To Write Captions That Spark Conversations
How To Write Flash Fiction
How To Write Flash Fiction
a screenshot of a text description with the words what and how to use it
a screenshot of a text description with the words what and how to use it
How to Build a Personal Prompt Library That Saves You 5 Hours Every Week
How to Build a Personal Prompt Library That Saves You 5 Hours Every Week
Click to Explore: Master JSON Prompt Structuring in 2025
Click to Explore: Master JSON Prompt Structuring in 2025
Tiny Text Generator
Tiny Text Generator
Transform Your Writing Class with Writing Sprints!
Transform Your Writing Class with Writing Sprints!
Write Your RPG Notes in FocusWriter
Write Your RPG Notes in FocusWriter
Book Idea Generator
Book Idea Generator

import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.types._
import org.apache.spark.sql.functions._
import org.apache.spark.sql.Row

val spark = SparkSession.builder.appName("SparkMongoDataSet").getOrCreate()

val schema = List(StructField("id", LongType), StructField("name", StringType), StructField("age", IntegerType)).toStructType
val data = Seq("Alice", 25), ("Bob", 30)
val ds = spark.createDataset(data)( schema )

ds.write.format("com.mongodb.spark.sql.DefaultSource").option("database", "mydb").option("collection", "mycollection").mode("overwrite").save()

As you've seen, integrating Spark with MongoDB opens up numerous possibilities for data processing and storage. By mastering the methods discussed above, you can create robust data pipelines, analyze data in real-time, and derive meaningful insights from your business data.

The next step in your journey could be exploring MongoDB's Change Streams to process streaming data in real-time with Spark. Happy coding!