# Mongo

## Find Nearest Locations With MongoDB — How To? <a href="#id-89e1" id="id-89e1"></a>

![](/files/-MJwIcU323sEax-S4_Y7)

There are many ways to implement finding nearest locations by given **latitude and longitude** .

Some of the **implementations** can be achieved through a **backend logic**,

and the other ways can be done by **utilizing** some features(**Spatial Indexes**) provided by **DBMSs**’(Mysql, SQL, MongoDB,….etc).

**In this post I will explain by example how we can do it with MongoDB.**

> **What are Latitude and Longitude?** , You can find more from here <https://www.latlong.net/>

## How To ? <a href="#id-802d" id="id-802d"></a>

Let’s create a collection in MongoDb and we call it `locations` .

> To Achieve the query of **finding nearest locations by given latitude and longitude**, we do the following **Steps**:
>
> **First Step** : Each stored document must follow a structure called **GeoJSON .**
>
> **Second Step** : We have to create **2dsphere** Index in that collection .
>
> **Third Step** : We run the **Find query**! .

## First Step: GeoJSON <a href="#id-6efd" id="id-6efd"></a>

The `locations` collection will store a list of documents, each one of them represents a location(or an address) on the map.&#x20;

Each document will **follow** this example/structure:

```
{
  "country": "UAE",
  "city": "Dubai",
  "address": "Dubai Mall",
  "loc": {
    "type": "Point",
    "coordinates": [
      25.1973,//latitude
      55.2793 //longitude
    ]
  }
}
```

This Structure is following **GeoJSON Structure!**

— What’s **GeoJSON Structure?**

It is a JSON document that must have an object inside it , as follows :

```
<field>: { type: <GeoJSON type> , coordinates: <coordinates> }
```

Projection on the previous (Dubai Mall) document :

```
"loc" : {"type" : "Point" , "coordinates" : [25.1973,55.2793]}
```

> Read more about : **GeoJSON** Object <https://docs.mongodb.com/manual/reference/geojson/>

Ok, Great!, till now we’ve created `locations` collection that has a list of documents that follow **GeoJSON** structure, so let’s suppose we have those documents inside `locations`:

## **Second Step : Index Creation** <a href="#id-4b0e" id="id-4b0e"></a>

We need to run **createIndex** Command to tell MongoDb that this collection is following the **GeoJSON** structure, so we can achieve the query of finding nearest locations successfully.

Command syntax:

```
db.collection.createIndex( { <location field> : "2dsphere" } )
```

Projection:

```
db.locations.createIndex( { "loc" : "2dsphere" } )
```

## **Third Step :** Find Query <a href="#dad9" id="dad9"></a>

As Per MongoDb documentation, here is the syntax of finding nearest locations by given latitude/longitude:

```
db.collection.find(
{
   <location field>: {
     $near: {
       $geometry: {
          type: "Point" ,
          coordinates: [ <longitude> , <latitude> ]
       },
     }
   }
})
```

If I want to get the nearest locations to my current location, I should provide my current latitude/longitude, so let’s suppose

My Current Latitude: **25.087626** / Longitude: **55.151134 . (Dubai Marina)**

So when I query the collection, we do:

```
db.locations.find(
{
   "loc": {
     $near: {
       $geometry: {
          type: "Point" ,
          coordinates: [ 25.087626 , 55.151134 ]
       },
     }
   }
})
```

**Query Result: (ordered by nearest, according to my Latitude :25.087626/Longitude : 55.151134)**

This is it!, Hope you find this information useful!

```
db.collectionname.find({
    "location": {
        $near: {
            $geometry:
                { type: "Point", coordinates: [50.0, -0.1330] }, $maxDistance: 500
        }
    }
})

db.address.find ({
  location: {
     $near: {
       $geometry: {
          type: "Point" ,
          coordinates: [ -72.7738706,41.6332836 ]
       },
       $maxDistance: 4,
       $minDistance: 0
     }
   }
})
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://tritueviet.gitbook.io/server/master.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
