<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Vivek Bharatha on Medium]]></title>
        <description><![CDATA[Stories by Vivek Bharatha on Medium]]></description>
        <link>https://medium.com/@vivek.bharatha?source=rss-5457640f8d95------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*G-n8TGrQyerN7mmxpjT3cw.jpeg</url>
            <title>Stories by Vivek Bharatha on Medium</title>
            <link>https://medium.com/@vivek.bharatha?source=rss-5457640f8d95------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 12:49:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vivek.bharatha/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to add new keys to 50 Million+ records using MongoDB Streams]]></title>
            <link>https://medium.com/@vivek.bharatha/how-to-add-new-keys-to-50-million-records-using-mongodb-streams-f0bd56ed2c25?source=rss-5457640f8d95------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0bd56ed2c25</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[migration]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Vivek Bharatha]]></dc:creator>
            <pubDate>Thu, 04 May 2023 07:36:18 GMT</pubDate>
            <atom:updated>2023-05-04T07:36:18.702Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b6gtiPyV21SEyuq0" /><figcaption>Photo by <a href="https://unsplash.com/@fabioha?utm_source=medium&amp;utm_medium=referral">fabio</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>MongoDB is a popular NoSQL database that is widely used for building scalable applications. As your application grows and evolves, you may need to make changes to your MongoDB collections, such as adding a new field to your documents. Migrating large MongoDB collections can be a challenging task, especially when dealing with millions of records.</p><p>In this article, we’ll explore how to use Node.js and MongoDB streams to efficiently migrate large MongoDB collections. We’ll demonstrate how to add two new keys to a MongoDB collection with 10 million+ records using streams and compare this approach to using cursors.</p><h3>Adding a new keys to a MongoDB Collection</h3><p>Let’s start with an example scenario where we need to add a new key to a MongoDB collection with 10 million+ records. We can accomplish this task using Node.js and MongoDB updateOne() method, which allows us to update a single document in a collection. Here&#39;s an example Node.js script that adds new keys to a MongoDB collection using a cursor:</p><p>Sample record:</p><pre>{<br>  &quot;name&quot;: &quot;vivek bharatha&quot;,<br>  &quot;address1&quot;: &quot;horizon&quot;,<br>  &quot;address2&quot;: &quot;cityName, StateName&quot;<br>}</pre><pre>const { MongoClient } = require(&quot;mongodb&quot;);<br>const logger = require(&quot;log4js&quot;).getLogger();<br>logger.level = &#39;debug&#39;;<br><br>const uri = &quot;mongodb://localhost:27017&quot;;<br>const dbName = &quot;v-bank&quot;;<br>const collectionName = &quot;users&quot;;<br><br>(async () =&gt; {<br>  const client = new MongoClient(uri);<br>  await client.connect();<br><br>  const db = client.db(dbName);<br>  const collection = db.collection(collectionName);<br>  const query = { state: { $exists: false } };<br>  const count = await collection.countDocuments(query);<br>  logger.info(`Total records to process: ${count}`);<br>  const cursor = collection.find(query);<br>  let processed = 0;<br><br>  try {<br>    while (await cursor.hasNext()) {<br>      const doc = await cursor.next();<br>      const [city, state] = doc.address2.split(&quot;, &quot;);<br>      const result = await collection.updateOne(<br>        { _id: doc._id },<br>        { $set: { state, city } }<br>      );<br>      if (result.modifiedCount) {<br>        processed += result.modifiedCount;<br>      }<br><br>      logger.info(`Percentage completed: ${((processed / count) * 100).toFixed(3)} %`);<br>    }<br><br>    logger.info(&quot;Migration completed successfully&quot;);<br>  } catch (err) {<br>    logger.error(err);<br>  } finally {<br>    await client.close();<br>  }<br>})();</pre><p>This script iterates over the documents in the collection using a cursor and adds a new key to each document using MongoDB’s updateOne() method. While this approach works for smaller collections, it can be slow and overloaded on the database instance side as we send the request to update for every document and affect the whole application performance.</p><h3>Using MongoDB Streams to Migrate Large Collections</h3><p>MongoDB streams are a powerful feature of Node.js that allows you to process large collections efficiently. Using streams can be a more memory-efficient and performant approach than using cursors, especially when dealing with large collections.</p><p>To use streams to migrate a MongoDB collection, we’ll create a read stream to read the documents from the collection, and a write stream to add the new keys to each document. We’ll then pipe the read stream to the write stream, which will process the documents as they arrive.</p><p>Here’s an example Node.js script that uses MongoDB streams to add a new key to a MongoDB collection with 10 million+ records:</p><pre>const { MongoClient } = require(&quot;mongodb&quot;);<br>const { Transform } = require(&quot;stream&quot;);<br>const logger = require(&quot;log4js&quot;).getLogger();<br>logger.level = &#39;debug&#39;;<br><br>const uri = &quot;mongodb://localhost:27017&quot;;<br>const dbName = &quot;v-bank&quot;;<br>const collectionName = &quot;users&quot;;<br>const batchSize = 100_000;<br><br>(async () =&gt; {<br>  const client = new MongoClient(uri);<br>  await client.connect();<br><br>  const db = client.db(dbName);<br>  const collection = db.collection(collectionName);<br>  const query = { state: { $exists: false } };<br>  const totalRecordsToProcess = await collection.countDocuments(query);<br>  logger.info(`Total records to process: ${totalRecordsToProcess}`);<br><br>  let count = 0;<br>  let processed = 0;<br><br>  const docTransformStream = new Transform({<br>    objectMode: true,<br>    transform: async function (doc, encoding, callback) {<br>      try {<br>        const [city, state] = doc.address2.split(&quot;, &quot;);<br>        doc.city = city;<br>        doc.state = state;<br>        this.push(doc);<br>        callback();<br>      } catch (err) {<br>        logger.info(err + `for doc id: ${doc._id}`);<br>        callback();<br>      }<br>    },<br>  });<br><br>  const readStream = collection.find(query).stream();<br>  let updateStream = collection.initializeUnorderedBulkOp();<br><br>  readStream<br>    .pipe(docTransformStream)<br>    .on(&quot;data&quot;, async (doc) =&gt; {<br>      updateStream<br>        .find({ _id: doc._id })<br>        .updateOne({ $set: { city: doc.city, state: doc.state } });<br>      count++;<br><br>      if (count % batchSize === 0) {<br>        readStream.pause();<br><br>        const result = await updateStream.execute();<br>        processed += result.nModified;<br><br>        logger.info(<br>          `Percentage completed: ${(<br>            (processed / totalRecordsToProcess) *<br>            100<br>          ).toFixed(3)} %`<br>        );<br><br>        updateStream = collection.initializeUnorderedBulkOp();<br>        readStream.resume();<br>      }<br>    })<br>    .on(&quot;error&quot;, logger.error)<br>    .on(&quot;end&quot;, async () =&gt; {<br>      if (count % batchSize !== 0) {<br>        const result = await updateStream.execute();<br>        processed += result.nModified;<br>        logger.info(`Updated ${result.nModified} records`);<br><br>        logger.info(`Total records modified: ${processed}`);<br>        client.close();<br>      }<br>    });<br>})();</pre><p>In this script, we convert the find query to stream as <strong>readStream</strong>. The docTransformStream transform function adds the new keys to each doc and we hook on <strong>data, error</strong> and <strong>end</strong> listeners.</p><p>We use bulkOp API to update docs in the bulk of batchSize<strong>.</strong> Initialize BulkOp stream as updateStream. Once it reaches a batchSize we <strong>execute</strong> the bulkOp and re-initialize with a new bulkOp object.</p><p>As we have async ops in the data handler function, data handler function won’t wait to process the async op to finish it just keeps receiving the data, to handle it correctly we pause and resume the stream once we hit batch size to execute bulk Op.</p><p>Finally, on the end listener, we check if any last chunk of records are there and process the same.</p><h3>Conclusion</h3><p>Migrating MongoDB collections can be a complex and challenging task, especially when dealing with large collections. In this article, we explored how to use Node.js and MongoDB streams to efficiently migrate large MongoDB collections. We demonstrated how to add a new key to a MongoDB collection with 10 million+ records using streams, and compared this approach to using cursors.</p><p>By using streams and bulkWrite(), we were able to efficiently process the documents in the collection without loading all the data into memory at once, and sending updates in batches resulting in faster and more memory-efficient migrations.</p><p>NOTE:<br>There are some assumptions here like<br>- the new keys are not being used in the application level during migration<br>- every address2 field will always have the <strong>city</strong> and <strong>state</strong> name with a pattern “<strong>city, state</strong>”<br>- You might wonder if batchSize defined in the above script is <strong>100K</strong> which is not an ideal batch size but based on the testing on lower environments like Staging, UAT you could narrow it down to a sweet point considering the large dataset of 50M+ records.</p><blockquote><strong><em>👋 If you found this information helpful, please consider showing your appreciation and sharing it with others who might benefit from it as well. Your support motivates me to continue creating useful content. Thank you!</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0bd56ed2c25" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debug Node JS in Docker container with VS Code]]></title>
            <link>https://medium.com/@vivek.bharatha/debug-node-js-in-docker-container-with-vs-code-f05febf91116?source=rss-5457640f8d95------2</link>
            <guid isPermaLink="false">https://medium.com/p/f05febf91116</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[vscode]]></category>
            <dc:creator><![CDATA[Vivek Bharatha]]></dc:creator>
            <pubDate>Sat, 18 May 2019 04:56:37 GMT</pubDate>
            <atom:updated>2019-05-18T05:14:32.118Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello…. everyone, hope you are awesome!</p><p>I recently switched to VS Code for my development, and new to docker based development.</p><p>Today I would like to share on how to debug the node js app inside docker container with vscode.</p><p>Let’s get started…..</p><p>First things first, let’s have a small node js server, use the below code snippet or use your own existing code-base.</p><p>And follow below configurations to setup Dockerfile and docker-compose.yml and configure the ports as per your wish</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be22b680655557199e735e9b0607eaea/href">https://medium.com/media/be22b680655557199e735e9b0607eaea/href</a></iframe><p>Add a configuration as shown above for launch.json in vscode.</p><p>Once you have everything in place you might have the files as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*j8emD4MAQQ7-FI7qbk5GsQ.png" /></figure><p>Once you are confident that all the files are in place and ready to debug!</p><p>Then build the image and run the container with below command</p><pre>docker-compose up -d</pre><p>Once it’s up you can see the status with vscode docker plugin as show below or you can use cli commands.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*OXwPVMGN4fPTfBZGHO4bEQ.png" /></figure><p>Docker plugin is very helpful, which gives the functionality of restarting the container, viewing logs and lots of other cool stuff.</p><blockquote>As we have used <strong>— inspect-brk</strong></blockquote><p>Process will be waiting to start the debugging, once you start the debugging process then the node process will hold at the first point of execution and you can keep debug points and debug the process!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0RQkCn_jjaJtt-rBLD0UTQ.png" /></figure><blockquote><strong>Very Important</strong></blockquote><p>As we are using <strong>nodemon</strong> to restart the node process when any file changes are made, if you observe the <strong>launch.json</strong> script, we have given a <strong>restart </strong>flag to <strong>true</strong>, which is very helpful to automatically connect the debugger to process whenever the node process gets restarted.</p><p><strong>NOTE</strong>: Given host as <strong>0.0.0.0</strong> which is for all the networks access you can restrict to your ip only.</p><p>If this article helped you, clap for me which motivates me to write more technical articles.</p><p>If you want any articles / guides let me know in below comments am ready for it :P</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f05febf91116" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[console.log Timestamp Hack!]]></title>
            <link>https://medium.com/@vivek.bharatha/console-log-timestamp-hack-a90d1ca83600?source=rss-5457640f8d95------2</link>
            <guid isPermaLink="false">https://medium.com/p/a90d1ca83600</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[js]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Vivek Bharatha]]></dc:creator>
            <pubDate>Wed, 06 Sep 2017 15:10:46 GMT</pubDate>
            <atom:updated>2024-07-08T08:46:07.322Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello! JS Geeks! Thank you so much for peeking into this article ;)<br>This will help you to hack console.log so that it automatically prepends timestamp for each and every console.log execution where you have already implemented.</p><p>Video version if you want to checkout —</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FFXmc9Z8w-_4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DFXmc9Z8w-_4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FFXmc9Z8w-_4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/171ed276ba179f7e7dca101f12e146d8/href">https://medium.com/media/171ed276ba179f7e7dca101f12e146d8/href</a></iframe><p>You think like why the heck we would be using the console.log function when we have enough logger packages like Winston etc., but in small projects or MVPs, you would be in hunger to complete features instead of concentrating on logs so you would be using console.log for debugging or some info related stuff.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*UE8wnuAFFqfSRVHssWxyXA.jpeg" /></figure><p>We will be using two core concepts one is <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments">function arguments object</a> and the other is <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply">apply method</a>.</p><p>Enough of theory, let’s get into coding!</p><p>Lets’s create a JS file as <strong><em>consoleTimestamp.js</em></strong>, we are overwriting the console.log function so let’s just save the original function in some variable like <strong>originalLog</strong> make sure this is not there in global scope to avoid conflicts!</p><pre>originalLog = console.log;</pre><p>Then lets overwrite our console.log function with skeleton block.</p><pre>originalLog = console.log;<br>// overwriting<br>console.log = function () {</pre><pre>};</pre><p>We need to get the timestamp whenever the console.log function is called so lets define the function.</p><pre>originalLog = console.log;<br>// overwriting<br>console.log = function () {</pre><pre>};<br>// Returns current timestamp<br>function getCurrentDateString() {<br>    return (new Date()).toISOString() + &#39; ::&#39;;<br>};</pre><p>If you observe I appended with “<strong> ::</strong>” for easy viewing of timestamps.</p><p>Now we need to get original arguments passed to console.log function in our entire code base! so lets grab arguments object and store in a variable.<br>But very important thing here we need to consider is arguments variable will be like array like object, not exactly an array.<br>We can get the actual arguments from the local arguments variable with simple slice function as mentioned in the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments">Arguments Doc</a>.</p><pre>originalLog = console.log;<br>// overwriting<br>console.log = function () {<br>    var args = [].slice.call(arguments);<br>};<br>// Returns current timestamp<br>function getCurrentDateString() {<br>    return (new Date()).toISOString() + &#39; ::&#39;;<br>};</pre><p>So till now we got the actual arguments passed to console.log function in our entire code base.</p><p>lets make use of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply">apply method</a> to invoke our previously saved originalLog function with console.log function scope.</p><pre>originalLog = console.log;<br>// overwriting<br>console.log = function () {<br>    var args = [].slice.call(arguments);<br>    originalLog.apply(console.log, args);<br>};<br>// Returns current timestamp<br>function getCurrentDateString() {<br>    return (new Date()).toISOString() + &#39; ::&#39;;<br>};</pre><p>Now we need to prepend the timestamp, lets get into that as well</p><pre>originalLog = console.log;<br>// Overwriting<br>console.log = function () {<br>    var args = [].slice.call(arguments);<br>    originalLog.apply(console.log,[getCurrentDateString()].concat(args));<br>};<br>// Returns current timestamp<br>function getCurrentDateString() {<br>    return (new Date()).toISOString() + &#39; ::&#39;;<br>};</pre><p>We are done with our prepending the timestamp, now lets implement this in our code base and check.<br>Before that let’s change<em> </em><strong><em>consoleTimestamp.js</em></strong> to module.</p><pre>module.exports = function () {<br>  originalLog = console.log;<br>  // Overwriting<br>  console.log = function () {<br>    var args = [].slice.call(arguments);<br>    originalLog.apply(console.log,[getCurrentDateString()].concat(args));<br>  };<br>  // Returns current timestamp<br>  function getCurrentDateString() {<br>    return (new Date()).toISOString() + &#39; ::&#39;;<br>  };<br>}</pre><p>Now for implementing this module, let’s suppose we have main <strong>app.js</strong> file in our project and lets require our hack module and invoke in the very first line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NA3GDQA91dSaOvnsNPoX7A.png" /><figcaption>Before using our module!</figcaption></figure><pre>require(&#39;./consoleTimestamp&#39;)();<br>var fileReader = require(&#39;./fileReader&#39;);</pre><pre>console.log(&#39;Reading README.md file&#39;);</pre><pre>fileReader.read(&#39;./README.md&#39;, function (err, fileData) {<br> if (err) {<br>  console.log(err);<br>  process.exit(1);<br> }</pre><pre>console.log(&#39;File data is&#39;, fileData);<br> process.exit(0);<br>});</pre><p>Observe that we invoked at the very first line not to miss even a single console.log to be hacked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cd_U8c8PwtoIS-klp21d_w.png" /><figcaption>After using our module!</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*5KZ0BWY3B7SN_Qs_NUNEiw.jpeg" /></figure><p>VOILA !<br>If you feel this is useful make sure you <strong>CLAP</strong> for me and <strong>share</strong> this :)</p><p>Interested in learning the internals of Redis and building your own Redis-like server from scratch using vanilla Node.js?</p><p>Check out my comprehensive series on YouTube:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fvideoseries%3Flist%3DPL-P_hNzCQhQi-6BsYBHoXUW2V9j2b3ITa&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fplaylist%3Flist%3DPL-P_hNzCQhQi-6BsYBHoXUW2V9j2b3ITa&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fq9ekqm7UWYg%2Fhqdefault.jpg%3Fsqp%3D-oaymwEXCOADEI4CSFryq4qpAwkIARUAAIhCGAE%3D%26rs%3DAOn4CLDPkq6KDhaEcpMEqbL-l3MLvNu6rg%26days_since_epoch%3D19912&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="853" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c32c1db3c97c2d84e57c5848dce46de/href">https://medium.com/media/5c32c1db3c97c2d84e57c5848dce46de/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a90d1ca83600" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>