<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Java- Apache Spark mongo example - TheCodeBuzz</title>
	<atom:link href="https://thecodebuzz.com/tag/java-apache-spark-mongo-example/feed/" rel="self" type="application/rss+xml" />
	<link>https://thecodebuzz.com</link>
	<description>Best Practices for Software Development</description>
	<lastBuildDate>Sun, 18 Feb 2024 02:55:10 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://thecodebuzz.com/wp-content/uploads/2022/11/cropped-android-chrome-512x512-1-1-51x51.jpg</url>
	<title>Java- Apache Spark mongo example - TheCodeBuzz</title>
	<link>https://thecodebuzz.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Java- Apache Spark Connect to MongoDB</title>
		<link>https://thecodebuzz.com/java-apache-spark-connect-mongodb-read-write/</link>
					<comments>https://thecodebuzz.com/java-apache-spark-connect-mongodb-read-write/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sat, 20 Jan 2024 23:47:53 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Java- Apache Spark Connect to MongoDB]]></category>
		<category><![CDATA[Java- Apache Spark mongo example]]></category>
		<guid isPermaLink="false">https://www.thecodebuzz.com/?p=29823</guid>

					<description><![CDATA[<p>Java- Apache Spark Connect to MongoDB Today in this article, we will see how to perform Java- Apache Spark Connect to MongoDB with examples. We will make use of MongoDB Spark Connector which helps connect to MongoDB and allows us to read and write data between Java and MongoDB. Here&#8217;s a basic example demonstrating how [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/java-apache-spark-connect-mongodb-read-write/">Java- Apache Spark Connect to MongoDB</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading"><strong>Java- Apache Spark Connect to MongoDB</strong></h1>



<figure class="wp-block-image size-large is-resized"><img fetchpriority="high" decoding="async" width="1024" height="361" src="https://www.thecodebuzz.com/wp-content/uploads/2024/01/Java-Spark-MongoDB-read-write-example-1024x361.jpg" alt="Java- Apache Spark Connect to MongoDB" class="wp-image-29834" style="width:776px;height:auto" srcset="https://thecodebuzz.com/wp-content/uploads/2024/01/Java-Spark-MongoDB-read-write-example-1024x361.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2024/01/Java-Spark-MongoDB-read-write-example-300x106.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2024/01/Java-Spark-MongoDB-read-write-example-768x271.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2024/01/Java-Spark-MongoDB-read-write-example-785x277.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2024/01/Java-Spark-MongoDB-read-write-example.jpg 1174w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>Today in this article, we will see how to perform Java- Apache Spark Connect to MongoDB with examples.</p>



<p></p>



<p>We will make use of MongoDB Spark Connector which helps connect to MongoDB and allows us to read and write data between Java and MongoDB.</p>



<p></p>



<p>Here&#8217;s a basic example demonstrating how to read data from MongoDB, perform a transformation, and then write the results back to MongoDB.</p>



<p></p>



<p>We have below MongoDB collection,</p>



<figure class="wp-block-image size-full"><img decoding="async" width="454" height="630" src="https://www.thecodebuzz.com/wp-content/uploads/2024/01/JAVA-Spark-to-connect-MongoDB-read-write.jpg" alt="" class="wp-image-29831" srcset="https://thecodebuzz.com/wp-content/uploads/2024/01/JAVA-Spark-to-connect-MongoDB-read-write.jpg 454w, https://thecodebuzz.com/wp-content/uploads/2024/01/JAVA-Spark-to-connect-MongoDB-read-write-216x300.jpg 216w, https://thecodebuzz.com/wp-content/uploads/2024/01/JAVA-Spark-to-connect-MongoDB-read-write-375x520.jpg 375w" sizes="(max-width: 454px) 100vw, 454px" /></figure>



<p></p>



<h2 class="wp-block-heading">Install MongoDB Connector for Apache Spark in JAVA</h2>



<p></p>



<p>You can download the connector from the official MongoDB website or use Maven/Gradle to include it as a dependency in your project.</p>



<p></p>



<p>Please install MongoDB Spark Connector using the below command.</p>



<p></p>



<p><strong>Gradle Command</strong></p>



<p></p>



<pre class="wp-block-preformatted">implementation 'org.mongodb.spark:mongo-spark-connector_2.12:3.0.1' // Replace with the latest version
</pre>



<p></p>



<p><strong>Maven Dependency:</strong></p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
&lt;dependency&gt;
    &lt;groupId&gt;org.mongodb.spark&lt;/groupId&gt;
    &lt;artifactId&gt;mongo-spark-connector_2.12&lt;/artifactId&gt;
    &lt;version&gt;3.0.1&lt;/version&gt;
&lt;/dependency&gt;

</pre></div>


<p></p>



<p>Please replace the above using the latest version as supported </p>



<p></p>



<p>For more details please visit the official website: <a href="https://www.mongodb.com/products/spark-connector" target="_blank" rel="noopener" title="">https://www.mongodb.com/products/spark-connector</a></p>



<p></p>



<h2 class="wp-block-heading">Create a SparkSession Object</h2>



<p></p>



<p>Create a SparkSession Object to use for read and write operations,</p>



<p></p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.sql.*;
import org.bson.Document;
import java.util.HashMap;
import java.util.Map;


public class SparkMongoDBTheCodeBuzz {
    public static void main(String&#x5B;] args) {
        // Configure Spark
        SparkConf sparkConf = new SparkConf()
                .setAppName(&quot;MongoDB Spark Connector Example&quot;)
                .setMaster(&quot;local&#x5B;*]&quot;)
                .set(&quot;spark.mongodb.input.uri&quot;, &quot;mongodb://host/TheCodeBuzz.Orders&quot;&quot;)
                .set(&quot;spark.mongodb.output.uri&quot;, &quot;mongodb://host/TheCodeBuzz.Orders&quot;&quot;);

       // Create a SparkContext
        JavaSparkContext jsc = new JavaSparkContext(sparkConf);

        // Create a SparkSession
        SparkSession spark = SparkSession.builder().config(sparkConf).getOrCreate();





</pre></div>


<p></p>



<p>We create a Spark session with the MongoDB connector configurations. </p>



<p></p>



<p>We will use the above <code>SparkSession</code> object to read, and write data to MongoDB, etc.</p>



<p></p>



<h2 class="wp-block-heading">Read Data from MongoDB using Spark</h2>



<p></p>



<p>You must specify the following configuration settings to read from MongoDB:</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.sql.*;
import org.bson.Document;
import java.util.HashMap;
import java.util.Map;


public class SparkMongoDBTheCodeBuzz {
    public static void main(String&#x5B;] args) {
        // Configure Spark
        SparkConf sparkConf = new SparkConf()
                .setAppName(&quot;MongoDB Spark Connector Example&quot;)
                .setMaster(&quot;local&#x5B;*]&quot;)
                .set(&quot;spark.mongodb.input.uri&quot;, &quot;mongodb://host/TheCodeBuzz.Orders&quot;&quot;)
                .set(&quot;spark.mongodb.output.uri&quot;, &quot;mongodb://host/TheCodeBuzz.Orders&quot;&quot;);

      // Create a SparkContext
        JavaSparkContext jsc = new JavaSparkContext(sparkConf);

        // Create a SparkSession
        SparkSession spark = SparkSession.builder().config(sparkConf).getOrCreate();

        // Read data from MongoDB
        JavaRDD&lt;Document&gt; mongoRDD = MongoSpark.load(jsc);

        // Perform transformations or analyses as needed
        // For example, you can convert the RDD to a DataFrame
        Dataset&lt;Row&gt; mongoDF = spark.createDataFrame(mongoRDD, Document.class);

        // Show the data
        mongoDF.show();
}
</pre></div>


<p></p>



<h2 class="wp-block-heading">Write data to MongoDB using Java Spark</h2>



<p></p>



<p>To write data from MongoDB, call the&nbsp;write function on your&nbsp;SparkSession&nbsp;object. </p>



<p></p>



<p>You must specify the following configuration settings to read from MongoDB,</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
data = &#x5B;
  {

    &quot;Order&quot;: &quot;journal2&quot;,
    &quot;qty&quot;: 25,
    &quot;books&quot;: &#x5B;
      &quot;white&quot;
    ],
    &quot;domain&quot;: &#x5B;
      14
    ],
    &quot;Link&quot;: &quot;https://www.thecodebuzz.com/order/23456&quot;
  },
  {

    &quot;Order&quot;: &quot;journal1&quot;,
    &quot;qty&quot;: 25,
    &quot;books&quot;: &#x5B;
      &quot;black&quot;
    ],
    &quot;domain&quot;: &#x5B;
      15
    ],
    &quot;Link&quot;: &quot;https://www.thecodebuzz.com/order/2324&quot;
  }
]
</pre></div>


<p></p>



<p></p>



<p>Let&#8217;s save this JSON file in any temporary location and access it  </p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">


       // Assume df is a DataFrame with the data you want to write to MongoDB
        Dataset&lt;Row&gt; df = spark.read().json(&quot;path/to/json/file&quot;);

        // Write data to MongoDB
        MongoSpark.write(df).option(&quot;TheCodeBuzz&quot;, &quot;Orders&quot;).mode(&quot;append&quot;).save();

        // Stop the Spark session
        spark.stop();


</pre></div>


<p></p>



<p>That&#8217;s all! Happy coding!</p>



<p></p>



<p>Does this help you fix your issue? </p>



<p></p>



<p>Do you have any better solutions or suggestions? Please sound off your comments below.</p>



<p></p>



<hr>



<p class=""></p>



<p class="has-background" style="background-color:#b6d9ac;font-size:18px"><br>Please <strong><em>bookmark </em></strong>this page and <em><strong>share </strong></em>it with your friends.                                                    Please <a href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noreferrer noopener"><em><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-orange-color"><strong>Subscribe</strong> </mark></em></a>to the blog to receive notifications on freshly published (2025) best practices and guidelines for software design and development.</p>




<br>



<hr>



<p class=""></p>



<p></p>



<p></p><p>The post <a href="https://thecodebuzz.com/java-apache-spark-connect-mongodb-read-write/">Java- Apache Spark Connect to MongoDB</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/java-apache-spark-connect-mongodb-read-write/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
