0
0
MongoDBquery~10 mins

Geospatial queries basics in MongoDB - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Geospatial queries basics
Start with a collection having location data
Create geospatial index on location field
Write geospatial query using $near, $geoWithin, or $geoIntersects
MongoDB uses index to find matching documents
Return documents matching spatial condition
End
This flow shows how MongoDB uses geospatial indexes to efficiently find documents near or within a specified location.
Execution Sample
MongoDB
db.places.createIndex({ location: "2dsphere" })
db.places.find({
  location: {
    $near: {
      $geometry: { type: "Point", coordinates: [ -73.9667, 40.78 ] },
      $maxDistance: 5000
    }
  }
})
Create a geospatial index and find places within 5 km of a point in New York.
Execution Table
StepActionInput/ConditionMongoDB OperationResult
1Create 2dsphere indexlocation fielddb.places.createIndex({ location: "2dsphere" })Index created on location
2Query with $nearPoint: [-73.9667, 40.78], maxDistance: 5000db.places.find({ location: { $near: { $geometry: ..., $maxDistance: 5000 } } })MongoDB uses index to find nearby documents
3Scan index for points within 5 kmUsing spherical geometryIndex scanDocuments sorted by distance returned
4Return matching documentsDocuments within 5 kmQuery resultList of places near the point
5EndNo more documentsQuery completeQuery finishes successfully
💡 Query ends after returning all documents within the specified maxDistance.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
Index on locationNone2dsphere index createdIndex ready for queryIndex scanned for matchesIndex used to return results
Query resultEmptyEmptyEmptyPartial list of documentsFinal list of nearby places
Key Moments - 3 Insights
Why do we need to create a 2dsphere index before running geospatial queries?
Without the 2dsphere index (see Step 1 in execution_table), MongoDB cannot efficiently find documents by location, so queries like $near will be slow or fail.
What does $maxDistance mean in the $near query?
$maxDistance limits the search radius to a maximum distance (in meters) from the point (see Step 2 and 3). Only documents within this distance are returned.
How does MongoDB return documents in a $near query?
MongoDB uses the geospatial index to scan and sort documents by distance from the point, returning them ordered nearest first (see Step 3 and 4).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what happens at Step 3?
AMongoDB creates the geospatial index
BMongoDB returns the final query results
CMongoDB scans the index for points within the maxDistance
DMongoDB finishes the query without scanning
💡 Hint
Refer to Step 3 in execution_table where index scanning is described.
According to variable_tracker, what is the state of 'Query result' after Step 2?
AContains all matching documents
BStill empty, query not executed yet
CPartial list of documents found
DFinal list of nearby places
💡 Hint
Check 'Query result' row in variable_tracker after Step 2.
If we remove the 2dsphere index creation (Step 1), what will happen to the query?
AQuery will fail or be very slow
BQuery will run faster
CQuery will return documents sorted by distance anyway
DQuery will ignore location field
💡 Hint
See key_moments about the importance of the 2dsphere index.
Concept Snapshot
Geospatial queries in MongoDB require a 2dsphere index on location fields.
Use $near to find documents close to a point, optionally with $maxDistance.
MongoDB uses the index to efficiently find and sort nearby documents.
Without the index, geospatial queries are slow or fail.
Results are returned ordered by distance from the query point.
Full Transcript
This visual execution trace shows how MongoDB performs basic geospatial queries. First, a 2dsphere index is created on the location field to enable efficient spatial searches. Then, a query using $near with a point and maxDistance finds documents near that point. MongoDB scans the geospatial index to find matching documents within the specified distance and returns them sorted by proximity. Variables like the index state and query results change step-by-step as the query runs. Key moments highlight why the index is necessary and how distance limits work. Quiz questions test understanding of the index usage, query progress, and effects of missing the index.