<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title>Coder Legion - Recent posts tagged js</title>
<link>https://coderlegion.com/tag/js</link>
<description>Powered by Question2Answer</description>
<item>
<title>Transformers.js: Running AI Models Directly in the Browser</title>
<link>https://coderlegion.com/30784/transformers-js-running-ai-models-directly-in-the-browser</link>
<description>&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://huggingface.co/docs/transformers.js/index&quot;&gt;Transformers.js&lt;/a&gt; is an open-source JavaScript library developed by Hugging Face that allows you to run pretrained machine learning models directly in web browsers and JavaScript runtimes such as Node.js, Deno, and Bun.&lt;/p&gt;
&lt;p&gt;It supports a variety of tasks, including text classification, sentiment analysis, image classification, audio processing, and feature extraction. It also allows developers to use many pretrained models from the Hugging Face Hub without having to build an inference backend from scratch.&lt;/p&gt;
&lt;p&gt;One of the most interesting features of Transformers.js is that models can run locally in the browser, depending on the model and available hardware. This can reduce reliance on external inference APIs and allow certain inputs to be processed on the user's device.&lt;/p&gt;
&lt;h3 id=&quot;how-does-transformers-js-work-&quot;&gt;How Does Transformers.js Work?&lt;/h3&gt;
&lt;p&gt;Transformers.js provides a &lt;code&gt;pipeline()&lt;/code&gt; API that simplifies loading a model and running inference for a particular task.&lt;/p&gt;
&lt;p&gt;For example, a text-classification pipeline can analyze a sentence and return a prediction:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-javascript&quot;&gt;import { pipeline } from '@huggingface/transformers';

const classifier = await pipeline(
  'sentiment-analysis',
  'Xenova/distilbert-base-uncased-finetuned-sst-2-english'
);

const result = await classifier(
  'Transformers.js makes AI more accessible to JavaScript developers.'
);

console.log(result);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;pipeline()&lt;/code&gt; function loads the selected model and prepares it for the specified task. You can then pass input to the pipeline and receive the model's predictions.&lt;/p&gt;
&lt;p&gt;The first execution may take some time because the model files need to be downloaded. Performance depends on the model size, runtime, and available hardware.&lt;/p&gt;
&lt;h3 id=&quot;what-can-you-build-with-it-&quot;&gt;What Can You Build With It?&lt;/h3&gt;
&lt;p&gt;Transformers.js supports a range of machine learning tasks, including:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Text:&lt;/strong&gt; sentiment analysis, text classification, and feature extraction.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Images:&lt;/strong&gt; image classification and other supported vision tasks.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Audio:&lt;/strong&gt; audio classification and speech-related tasks.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Embeddings:&lt;/strong&gt; converting text and other supported inputs into numerical representations for downstream applications.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The exact tasks and models available depend on the library version and model compatibility.&lt;/p&gt;
&lt;h3 id=&quot;things-to-consider&quot;&gt;Things to Consider&lt;/h3&gt;
&lt;p&gt;Running models locally has advantages, but it also comes with limitations. Model files can be large, inference may be slow on some devices, and not every model is suitable for browser execution.&lt;/p&gt;
&lt;p&gt;Local inference can reduce the need to send inputs to an external service, but it doesn't automatically make an entire application private or offline. Those properties also depend on how the application handles data and loads its resources.&lt;/p&gt;
&lt;h3 id=&quot;my-experience-with-transformers-js&quot;&gt;My Experience With Transformers.js&lt;/h3&gt;
&lt;p&gt;I explored Transformers.js while building EchoQuest, a small project that uses a pretrained audio-classification model to analyze recorded sounds in the browser.&lt;/p&gt;
&lt;p&gt;This gave me practical experience with model loading, audio preprocessing, and integrating machine learning into a JavaScript application without making an external inference API a core dependency.&lt;/p&gt;
&lt;p&gt;For JavaScript developers interested in machine learning, Transformers.js is a useful library to explore because it makes pretrained models accessible within familiar web development workflows.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Resources &amp;amp; Further Reading&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;EchoQuest:&lt;/strong&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://echoquest-qk1i.onrender.com/&quot;&gt;https://echoquest-qk1i.onrender.com/&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Documentation:&lt;/strong&gt; &lt;a rel=&quot;nofollow&quot; href=&quot;https://huggingface.co/docs/transformers.js/index&quot;&gt;https://huggingface.co/docs/transformers.js/index&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;GitHub:&lt;/strong&gt; &lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/huggingface/transformers.js&quot;&gt;https://github.com/huggingface/transformers.js&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Helpful Article:&lt;/strong&gt; &lt;a rel=&quot;nofollow&quot; href=&quot;https://blog.worldline.tech/2026/01/13/transformersjs-intro.html&quot;&gt;An Introduction to Transformers.js&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Image credit: Worldline Tech — &lt;a rel=&quot;nofollow&quot; href=&quot;https://blog.worldline.tech/2026/01/13/transformersjs-intro.html&quot;&gt;An Introduction to Transformers.js&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/30784/transformers-js-running-ai-models-directly-in-the-browser</guid>
<pubDate>Mon, 12 Oct 2026 08:17:37 +0000</pubDate>
</item>
<item>
<title>Intercepting Route In Next.js</title>
<link>https://coderlegion.com/27728/intercepting-route-in-next-js</link>
<description>&lt;h2 id=&quot;introduction&quot;&gt;Introduction&lt;/h2&gt;
&lt;p&gt;Intercepting route is a technique in Next.js that allows you to display a route from another part of your application, within the same current layout, without requiring the user to switch to a different context.&lt;/p&gt;
&lt;p&gt;Intercepting route is always used with  &lt;a rel=&quot;nofollow&quot; href=&quot;https://ali-abd-elbagi-v2.vercel.app/en-US/blog/parallel-route-in-next.js&quot;&gt;parallel route&lt;/a&gt; to build modals.&lt;/p&gt;
&lt;p&gt;For example, when you click on an image on Instagram, what happens is:&lt;/p&gt;
&lt;p&gt;1- A modal appears containing the image and its details, and the feed continues to run in the background.&lt;/p&gt;
&lt;p&gt;2- The link changes from &lt;a rel=&quot;nofollow&quot; href=&quot;https://www.instagram.com&quot;&gt;https://www.instagram.com&lt;/a&gt; to &lt;a rel=&quot;nofollow&quot; href=&quot;https://www.instagram.com/p/DYpin6_DOsV/&quot;&gt;https://www.instagram.com/p/DYpin6_DOsV/&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://coderlegion.com/?qa=blob&amp;amp;qa_blobid=2949956552825418224&quot; alt=&quot;&quot;&gt;&lt;br&gt;
&lt;img src=&quot;https://coderlegion.com/?qa=blob&amp;amp;qa_blobid=1417394263151395655&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;Intercepting route allows for the construction of this exact model: one link, and two different views depending on the user's approach.&lt;/p&gt;
&lt;h4 id=&quot;behind-the-scenes&quot;&gt;Behind the Scenes&lt;/h4&gt;
&lt;p&gt;What happens exactly is that Next.js intercepts the navigation request for the given page, and instead of displaying the page, it passes it to a specific @slot, which is the  &lt;a rel=&quot;nofollow&quot; href=&quot;https://ali-abd-elbagi-v2.vercel.app/en-US/blog/parallel-route-in-next.js&quot;&gt;Parallel Route&lt;/a&gt;&lt;/p&gt;
&lt;h4 id=&quot;folder-structure&quot;&gt;Folder Structure&lt;/h4&gt;
&lt;p&gt;The intercept route file is defined by creating a file that begins with (.), (..), or (..)(..), (...) where:&lt;/p&gt;
&lt;p&gt;(.) is used to match a segment at the same level.&lt;/p&gt;
&lt;p&gt;(..) is used to match a segment one level above.&lt;/p&gt;
&lt;p&gt;(..)(..) is used to match a segment at two levels above.&lt;/p&gt;
&lt;p&gt;(...) is used to match a segment at the root level. The importance of matching is evident when a user opens a new window or shares a link; the modal will not open, but the result will appear on a full standalone page. The intercept segment must match the full standalone page at the same level.&lt;/p&gt;
&lt;p&gt;It should also be noted that the intercept route (...) relies on the route segment for matching, not the file system. The segment is part of the URL, while the &lt;code&gt;@folder&lt;/code&gt; in the  &lt;a rel=&quot;nofollow&quot; href=&quot;https://ali-abd-elbagi-v2.vercel.app/en-US/blog/parallel-route-in-next.js&quot;&gt;Parallel Route&lt;/a&gt;is not considered part of the segment but rather a file system.&lt;/p&gt;
&lt;p&gt;The images below illustrate the file structure :&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://coderlegion.com/?qa=blob&amp;amp;qa_blobid=15782528588403846737&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://coderlegion.com/?qa=blob&amp;amp;qa_blobid=13279591298492409796&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h5 id=&quot;sources&quot;&gt;Sources&lt;/h5&gt;
&lt;p&gt;1- &lt;a rel=&quot;nofollow&quot; href=&quot;https://nextjs.org/docs/app/api-reference/file-conventions/intercepting-routes&quot;&gt;Next.js&lt;/a&gt;&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/27728/intercepting-route-in-next-js</guid>
<pubDate>Sat, 19 Sep 2026 10:14:13 +0000</pubDate>
</item>
<item>
<title>Poople Game</title>
<link>https://coderlegion.com/20616/poople-game</link>
<description>&lt;p&gt;Wordle proved that one small puzzle a day, shared by everyone and finished in about a minute, can quietly become a habit. Poople takes that same one-a-day rhythm and points it at a word ladder. You start from a 4-letter word and change one letter at a time until you reach POOP. Every rung along the way has to be a real 4-letter word, and the fewer steps you take, the better your score.&lt;/p&gt;
&lt;p&gt;The whole thing is free, runs in the browser, and needs no account. Your streak and stats live in your own browser, so there is nothing to sign up for and nothing to install. Open the page, solve the puzzle, copy a spoiler-free grid, and get on with your day.&lt;/p&gt;
&lt;h3 id=&quot;the-small-problem-it-solves&quot;&gt;The small problem it solves&lt;/h3&gt;
&lt;p&gt;Most of us already keep a little stack of daily puzzles we open with coffee. The friction shows up fast, though. Some games want an account before you can play. Some bury the puzzle under newsletters and pop-ups. Some take longer than the coffee does. Poople is built to be the opposite of all that. The page is light, the rules fit in one sentence, and a typical day takes under a minute.&lt;/p&gt;
&lt;h3 id=&quot;how-it-works&quot;&gt;How it works&lt;/h3&gt;
&lt;p&gt;A word ladder is an old idea. Lewis Carroll wrote about it in 1877 and called it Doublets. You connect two words by changing one letter at a time while keeping a valid word at every step. In Poople the destination is always POOP, which gives the game its name and a fixed target you can plan around. A new puzzle goes live every day at 08:00 UTC, and every player in the world gets the same starting word that day.&lt;/p&gt;
&lt;p&gt;What makes it satisfying is the planning. You are steering through a graph of words, looking a few moves ahead, and trying to land on the shortest route. It rewards a different muscle than a guessing game does, closer to finding a path through a maze than to filling in blanks.&lt;/p&gt;
&lt;h3 id=&quot;a-solve-looks-like-this&quot;&gt;A solve looks like this&lt;/h3&gt;
&lt;p&gt;Say the day's word is COAT.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;COAT becomes COAL&lt;/li&gt;
&lt;li&gt;COAL becomes COOL&lt;/li&gt;
&lt;li&gt;COOL becomes COOP&lt;/li&gt;
&lt;li&gt;COOP becomes POOP&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;That path takes four steps. There may be an even shorter route hiding in the dictionary, and par is that shortest possible path for the day. Matching par is the result to chase, and hunting for it is where the game gets its hooks into you.&lt;/p&gt;
&lt;h3 id=&quot;three-ways-to-play&quot;&gt;Three ways to play&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;The daily puzzle&lt;/strong&gt; is the main event. One shared word ladder for the whole world, refreshed every morning, with a spoiler-free grid you can post when you finish.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Poople Unlimited&lt;/strong&gt; is a free practice mode. Press shuffle for a fresh random starting word whenever you want, with no wait for the next day. It keeps your daily streak untouched, so it is a relaxed place to warm up before the daily puzzle or to keep going after you have solved it.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Poople Answers&lt;/strong&gt; is the archive. Once a puzzle closes, its full solution is published the next day. Each entry shows the verified shortest path, progressive hints you can reveal one at a time, short definitions for the bridge words along the way, and an in-page solver that finds the shortest route to POOP from any 4-letter word you type in.&lt;/p&gt;
&lt;h3 id=&quot;details-that-make-the-habit-stick&quot;&gt;Details that make the habit stick&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Spoiler-free sharing.&lt;/strong&gt; Copy a small grid that shows your path without giving away the words you used, in the same spirit as the Wordle share.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Local stats.&lt;/strong&gt; Wins, best streak, and average steps are saved on your device, so your history follows your browser instead of a login.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Keyboard and touch.&lt;/strong&gt; Type on a physical keyboard or tap the on-screen keys, on desktop or mobile.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Par scoring.&lt;/strong&gt; Every puzzle has a known shortest path, so there is always a clear goal beyond simply reaching POOP.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Fast and clean.&lt;/strong&gt; The page is light and free of clutter, so it loads quickly and starts the moment it opens.&lt;/p&gt;
&lt;p&gt;On price there is not much to cover. Poople is free, there is no account wall, and there is nothing to download. The daily game stays the daily game, and the practice mode and the archive sit alongside it for anyone who wants more.&lt;/p&gt;
&lt;h3 id=&quot;stack-notes-for-the-engineers-in-the-room&quot;&gt;Stack notes for the engineers in the room&lt;/h3&gt;
&lt;p&gt;Poople runs on Next.js 15 with the App Router, deployed to Cloudflare through OpenNext. Data lives in Cloudflare D1, which is SQLite, with Drizzle ORM on top, and the runtime leans on Cloudflare Workers, Durable Objects, KV, and R2. Copy and translations go through next-intl.&lt;/p&gt;
&lt;p&gt;The part I had the most fun building is the answers pipeline. The day's solution is never written by hand. A breadth-first search over the graph of every valid 4-letter word computes par and a verified shortest path, so each archived answer comes from one deterministic source of truth. A Cloudflare cron trigger publishes the previous day's answer every morning, and at the same time it generates the short bridge-word definitions and a one-line note for that puzzle through an LLM via OpenRouter, then stores them in D1 so the pages stay static and cheap to serve. Each past puzzle gets its own page at /answer/{number}-{word}, statically generated with incremental static regeneration, which turns the archive into a clean programmatic surface that grows by one page a day.&lt;/p&gt;
&lt;p&gt;On the roadmap: more variety in starting words, an optional harder mode, and a small public endpoint for the daily puzzle so people can build their own front-ends and bots around it.&lt;/p&gt;
&lt;h3 id=&quot;try-it&quot;&gt;Try it&lt;/h3&gt;
&lt;p&gt;Play today's puzzle at &lt;a rel=&quot;nofollow&quot; href=&quot;https://pooplegame.com&quot;&gt;https://pooplegame.com&lt;/a&gt;. The practice mode is at &lt;a rel=&quot;nofollow&quot; href=&quot;https://pooplegame.com/unlimited&quot;&gt;https://pooplegame.com/unlimited&lt;/a&gt;, and the answers archive is at &lt;a rel=&quot;nofollow&quot; href=&quot;https://pooplegame.com/answer&quot;&gt;https://pooplegame.com/answer&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;If you give it a try, I would love to hear two things. First, when you get stuck, what is your instinct, do you swap the vowel first or work backward from POOP? Second, for the developers here, would a daily-puzzle API be worth building out? Feedback and bug reports are very welcome.&lt;/p&gt;
</description>
<category>Launches</category>
<guid isPermaLink="true">https://coderlegion.com/20616/poople-game</guid>
<pubDate>Mon, 15 Jun 2026 05:36:21 +0000</pubDate>
</item>
<item>
<title>4 ways to query GeoJSON data in MongoDB</title>
<link>https://coderlegion.com/1672/4-ways-to-query-geojson-data-in-mongodb</link>
<description>&lt;p&gt;Have you ever heard of GeoJSON? If not, let me explain it to you.&lt;br&gt;
GeoJSON is a format for encoding a variety of geographic data structures created and published in 2008.&lt;/p&gt;
&lt;p&gt;Since 2015, it has an official &lt;a rel=&quot;nofollow&quot; href=&quot;https://tools.ietf.org/html/rfc7946&quot;&gt;specification&lt;/a&gt; created by its original authors with the collaboration of the Internet Engineering Task Force &lt;a rel=&quot;nofollow&quot; href=&quot;https://www.ietf.org/&quot;&gt;(IETF)&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;According to this specification:&lt;/p&gt;
&lt;blockquote&gt;&lt;p&gt;GeoJSON is a geospatial data interchange format based on JavaScript Object Notation (JSON).  It defines several types of JSON objects and the manner in which they are combined to represent data about geographic features, their properties, and their spatial extents. GeoJSON uses a geographic coordinate reference system, World Geodetic System 1984, and units of decimal degrees.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;It is a format widely used across JSON-based applications to read, manipulate and compare geospatial data.&lt;/p&gt;
&lt;p&gt;Several third-party map libraries provide GeoJSON support for front-end applications, some of them are:&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://leafletjs.com/reference-1.7.1.html#geojson&quot;&gt;Leaflet&lt;/a&gt;&lt;br&gt;
&lt;a rel=&quot;nofollow&quot; href=&quot;https://openlayers.org/en/latest/examples/geojson.html&quot;&gt;Openlayers&lt;/a&gt;&lt;br&gt;
&lt;a rel=&quot;nofollow&quot; href=&quot;https://developers.google.com/maps/documentation/javascript/datalayer#load_geojson&quot;&gt;Google Maps&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Considering that now you know a little bit more about GeoJSON, let´s move to the manipulation bit.&lt;br&gt;
When building maps for a web application, it is common to deal with something we call &quot;Layers&quot;. &lt;a rel=&quot;nofollow&quot; href=&quot;https://developers.google.com/maps/documentation/javascript/layers&quot;&gt;According to Google&lt;/a&gt;:&lt;/p&gt;
&lt;blockquote&gt;&lt;p&gt;Layers are objects on the map that consist of one or more separate items but are manipulated as a single unit. Layers generally reflect collections of objects that you add on top of the map to designate a common association.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;A Layer can have different formats and one of them is GeoJSON.&lt;/p&gt;
&lt;p&gt;So, when working with more than one layer in a map, it is common to perform operations between them to determine their geospatial relationship within a context. By making use of geospatial operations, it is possible to determine, for example, if:&lt;/p&gt;
&lt;p&gt;i) a Point lies within a Polygon;&lt;br&gt;
ii) a Polygon intersects another Polygon;&lt;br&gt;
iii) a Line crosses a circle;&lt;br&gt;
iv) a Point is part of a Line;&lt;/p&gt;
&lt;p&gt;But, depending on the size of the involved layers, manipulating or comparing them directly with JavaScript, in the browser, might cause performance issues since the memory usage tends to increase even more if they need to be rendered on a map.&lt;/p&gt;
&lt;p&gt;A good solution for this case is to perform any required geospatial operation directly in the database. Most of the database engines provide functions to query GeoJSON and one of them is &lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.mongodb.com/manual/reference/geojson/&quot;&gt;MongoDB&lt;/a&gt; which, by the way, has been pretty optimized for spatial operations since &lt;a rel=&quot;nofollow&quot; href=&quot;https://www.mongodb.com/blog/post/geospatial-performance-improvements-in-mongodb-3-2&quot;&gt;version 3.2&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;These are some of the most basic geospatial structures that MongoDB supports:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Point&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  &quot;type&quot;: &quot;Point&quot;,
  &quot;coordinates&quot;: [
    -42.53700256347656,
    -22.28496664336935
   ]
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Linestring&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  &quot;type&quot;: &quot;LineString&quot;,
  &quot;coordinates&quot;: [
    [
      -43.17626953125,
      -22.91792293614603
    ],
    [
      -40.2978515625,
      -20.262197124246534
    ]
  ]
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Polygon&lt;/strong&gt; &lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  &quot;type&quot;: &quot;Polygon&quot;,
  &quot;coordinates&quot;: [
    [
      [
        -42.94006347656249,
        -22.649502094242195
      ],
      [
        -42.16552734375,
        -22.649502094242195
      ],
      [
        -42.16552734375,
        -21.968519331082298
      ],
      [
        -42.94006347656249,
        -21.968519331082298
      ],
      [
        -42.94006347656249,
        -22.649502094242195
      ]
    ]
  ]
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Geometry Collection&lt;/strong&gt; &lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  type: &quot;GeometryCollection&quot;,
  geometries: [
    {
      &quot;type&quot;: &quot;Point&quot;,
      &quot;coordinates&quot;: [
        -42.53700256347656,
        -22.28496664336935
      ]
    },
    {
      &quot;type&quot;: &quot;LineString&quot;,
      &quot;coordinates&quot;: [
        [
          -43.17626953125,
          -22.91792293614603
        ],
        [
          -40.2978515625,
          -20.262197124246534
        ]
      ]
    },
    {
      &quot;type&quot;: &quot;Polygon&quot;,
      &quot;coordinates&quot;: [
        [
          [
            -42.94006347656249,
            -22.649502094242195
          ],
          [
            -42.16552734375,
            -22.649502094242195
          ],
          [
            -42.16552734375,
            -21.968519331082298
          ],
          [
            -42.94006347656249,
            -21.968519331082298
          ],
          [
            -42.94006347656249,
            -22.649502094242195
          ]
        ]
      ]
    }
  ]
}
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;http://geojson.io/#id=gist:vcpablo/2758df2cb48a5b1031b77a18c60cea9d&amp;amp;map=8/-21.596/-41.737&quot;&gt;Here&lt;/a&gt; you can find the mentioned examples plotted in a map using geojson.io.&lt;/p&gt;
&lt;p&gt;Now, I'm going to show you some basic operations that can be performed directly in a Mongo database assuming that there is already a collection named &lt;code&gt;geospatial&lt;/code&gt; with the &lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.mongodb.com/manual/core/2dsphere/&quot;&gt;proper indexes&lt;/a&gt; set up.&lt;/p&gt;
&lt;p&gt;To ease the query implementation, I recommend setting the GeoJSON object inside a property of your document. In the following example, the property &quot;location&quot; represents the geometry: &lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  &quot;$id&quot;: &quot;342j3ug4kj23b4k234&quot;
  &quot;location&quot;: {
    &quot;type&quot;: &quot;Point&quot;,
    &quot;coordinates&quot;: [ -22, -42 ]
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;1-finding-geometries-that-intersect-with-the-given-point&quot;&gt;1. Finding geometries that intersect with the given Point&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;db.geospatial.find({
  location: {
    $geoIntersects: {
     $geometry: {
       type: &quot;Point&quot;,
       coordinates: [
         -42.53700256347656,
         -22.28496664336935
        ]
      }
    }
  }
})
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This query will retrieve all geometries with which the given Point intersects. This example shows a query passing a Point as a parameter, but it supports any &lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.mongodb.com/manual/reference/geojson/&quot;&gt;GeoJSON Object&lt;/a&gt;&lt;/p&gt;
&lt;h3 id=&quot;2-finding-all-geometries-that-lie-within-a-given-geometry&quot;&gt;2. Finding all geometries that lie within a given geometry&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;db.geospatial.find({
  location: {
    $geoWithin: {
      $geometry: {
        &quot;type&quot;: &quot;Polygon&quot;,
        &quot;coordinates&quot;: [
          [
            [
              -42.94006347656249,
              -22.649502094242195
            ],
            [
              -42.16552734375,
              -22.649502094242195
            ],
            [
              -42.16552734375,
              -21.968519331082298
            ],
            [
              -42.94006347656249,
              -21.968519331082298
            ],
            [
              -42.94006347656249,
              -22.649502094242195
            ]
          ]
        ]
      }
  }
    }
})
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This query will retrieve all geometries that are inside the given Polygon and it is useful to look for all points that are placed within an area. For example: let's say you'd like to find all restaurants in a given city.&lt;/p&gt;
&lt;h3 id=&quot;3-finding-geometries-within-a-number-of-miles-from-a-given-point&quot;&gt;3. Finding geometries within a number of miles from a given point&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;db.geospatial.find({
  location: {
    $geoWithin: {
      $centerSphere: [
        [ -42.53700256347656, -22.28496664336935 ],
        5 / 3963.2
      ]
    }
  }
})
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Using &lt;code&gt;$centerSphere&lt;/code&gt;, MongoDB will &quot;draw&quot; a circle with a pre-defined size from a given point. In this case, the query will retrieve all geometries that are up to 5 miles to the coordinates provided.&lt;br&gt;
It is important to mention that, in this case, the geometries will be retrieved unordered.&lt;/p&gt;
&lt;h3 id=&quot;4-finding-ordered-geometries-within-a-number-of-miles-from-a-given-point&quot;&gt;4. Finding &lt;em&gt;ordered&lt;/em&gt; geometries within a number of miles from a given point&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;const METERS_PER_MILE = 1609.34

db.geospatial.find({
  location: {
    $nearSphere: {
      $geometry: {
        type: &quot;Point&quot;,
        coordinates: [ -73.93414657, 40.82302903 ]
      },
      $maxDistance: 5 * 1609.34
    }
  }
})
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This query will retrieve the same result as the previous one, but order from the nearest to the farthest.&lt;br&gt;
Check &lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.mongodb.com/manual/tutorial/calculate-distances-using-spherical-geometry-with-2d-geospatial-indexes/&quot;&gt;this page&lt;/a&gt; for more information on distance unit conversion.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;GeoJSON is the most used format to represent Geospatial data in web applications. It is fully supported by the most popular third-party map rendering libraries and database engines.&lt;/p&gt;
&lt;p&gt;This article demonstrated some basic concepts and how to implement some of the spatial operations provided by MongoDB.&lt;/p&gt;
&lt;p&gt;I hope you've liked it.&lt;br&gt;
Please, share and comment... any feedback is welcome!&lt;/p&gt;
</description>
<category>Queries</category>
<guid isPermaLink="true">https://coderlegion.com/1672/4-ways-to-query-geojson-data-in-mongodb</guid>
<pubDate>Tue, 25 Mar 2025 23:51:49 +0000</pubDate>
</item>
</channel>
</rss>