Geolocation Based Search

Friday, March 10th 2023

Here's an example of a geolocation-based search using MongoDB:

Suppose we have a collection of stores with documents that look like this:

{ "_id": ObjectId("61dfcb8452c3f3cbbcd0d53a"), "name": "MyStore", "location": { "type": "Point", "coordinates": [-73.9749, 40.7736] } }

The location field is a geospatial index that uses the "Point" data type to store the longitude and latitude of each store.

To search for stores near a given location, we can use MongoDB's $geoNear aggregation stage. Here's an example:

db.stores.aggregate([ { $geoNear: { near: { type: "Point", coordinates: [-73.9866, 40.7588] }, distanceField: "distance", spherical: true } }, { $match: { distance: { $lt: 5000 } } } ])

In this example, we're searching for stores within 5 kilometers of the location with longitude -73.9866 and latitude 40.7588. Here's what each part of the pipeline does:

  • $geoNear: This stage calculates the distance between each store's location and the search location, and adds a distance field to each document. The near parameter specifies the search location, and the spherical parameter indicates that we're working with a spherical coordinate system (i.e., the Earth's surface).
  • $match: This stage filters the results to include only stores within the specified distance. In this case, we're including only stores with a distance field less than 5,000 meters (or 5 kilometers).

The resulting documents will include a distance field that indicates the distance in meters between each store and the search location.

Note that this example assumes that you have already created a geospatial index on the location field. You can create a geospatial index with the following command:

db.stores.createIndex({ location: "2dsphere" })

This creates a geospatial index on the location field using the "2dsphere" index type, which supports searches on a spherical Earth model.