Bird
Raised Fist0
MongoDBquery~10 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What does the $near operator do in MongoDB geospatial queries?
easy
A. Finds documents with locations closest to a specified point
B. Deletes documents within a certain distance
C. Updates documents with new coordinates
D. Sorts documents alphabetically by location name

Solution

  1. Step 1: Understand the purpose of $near

    The $near operator is used to find documents that are geographically close to a given point.
  2. Step 2: Compare options with $near functionality

    Only Finds documents with locations closest to a specified point correctly describes finding documents near a location. Other options describe unrelated actions.
  3. Final Answer:

    Finds documents with locations closest to a specified point -> Option A
  4. Quick Check:

    $near = Finds nearby points [OK]
Hint: Remember: $near finds closest points to a location [OK]
Common Mistakes:
  • Thinking $near deletes or updates documents
  • Confusing $near with sorting operators
  • Assuming $near works without a geospatial index
2. Which of the following is the correct syntax to find documents near a point using $near in MongoDB?
easy
A. { location: { $near: { $geometry: { type: 'Point', coordinates: [-70, 40] } } } }
B. { location: { $near: { $geometry: { type: 'Point', coordinates: [40, -70] } } } }
C. { location: { $near: { $geometry: { type: 'Point', coordinates: [70, 40] } } } }
D. { location: { $near: { $geometry: { type: 'Point', coordinates: [-40, 70] } } } }

Solution

  1. Step 1: Recall coordinate order in MongoDB

    Coordinates must be in [longitude, latitude] order, so longitude comes first.
  2. Step 2: Check each option's coordinate order

    { location: { $near: { $geometry: { type: 'Point', coordinates: [-70, 40] } } } } uses [-70, 40], which is [longitude, latitude]. Others have latitude first or wrong signs.
  3. Final Answer:

    { location: { $near: { $geometry: { type: 'Point', coordinates: [-70, 40] } } } } -> Option A
  4. Quick Check:

    Coordinates = [longitude, latitude] [OK]
Hint: Coordinates always [longitude, latitude] in MongoDB [OK]
Common Mistakes:
  • Swapping latitude and longitude order
  • Using positive latitude as longitude
  • Forgetting to use $geometry inside $near
3. Given a collection with a 2dsphere index on location, what will this query return?
{ location: { $near: { $geometry: { type: 'Point', coordinates: [-73.97, 40.77] }, $maxDistance: 500 } } }
medium
A. All documents regardless of location
B. Documents with locations within 500 meters of [-73.97, 40.77]
C. Documents with locations more than 500 meters away
D. Documents with locations exactly at [-73.97, 40.77]

Solution

  1. Step 1: Understand $near with $maxDistance

    The query finds documents near the point within the maximum distance specified (500 meters).
  2. Step 2: Interpret the query result

    It returns documents whose location is within 500 meters of the given coordinates, not exactly at or beyond that distance.
  3. Final Answer:

    Documents with locations within 500 meters of [-73.97, 40.77] -> Option B
  4. Quick Check:

    $near + $maxDistance = nearby points within distance [OK]
Hint: Use $maxDistance to limit how far results can be [OK]
Common Mistakes:
  • Thinking $maxDistance means exact match
  • Assuming it returns points beyond maxDistance
  • Ignoring the need for a 2dsphere index
4. You run this query but get an error:
{ location: { $near: { $geometry: { type: 'Point', coordinates: [40.77, -73.97] } } } }

What is the most likely cause?
medium
A. Coordinates are in wrong order; should be [longitude, latitude]
B. Missing $maxDistance parameter
C. The location field is not indexed with 2dsphere
D. The type should be 'Polygon' instead of 'Point'

Solution

  1. Step 1: Requirements for $near with $geometry

    The $near operator with $geometry requires a 2dsphere index on the location field.
  2. Step 2: Identify the most likely error cause

    Without a 2dsphere index, MongoDB throws an error for geospatial queries like $near. Coordinate order affects results but does not cause an error.
  3. Final Answer:

    The location field is not indexed with 2dsphere -> Option C
  4. Quick Check:

    $near requires 2dsphere index [OK]
Hint: Always put longitude before latitude in coordinates [OK]
Common Mistakes:
  • Swapping latitude and longitude
  • Assuming $maxDistance is required
  • Confusing geometry types
5. You want to find all restaurants within 1 km of a user's location stored as { type: 'Point', coordinates: [-122.42, 37.77] }. Which query correctly finds these restaurants assuming a 2dsphere index on location?
hard
A. { location: { $near: { $geometry: { type: 'Point', coordinates: [-122.42, 37.77] }, $minDistance: 1000 } } }
B. { location: { $geoWithin: { $centerSphere: [[-122.42, 37.77], 1] } } }
C. { location: { $nearSphere: { $geometry: { type: 'Point', coordinates: [37.77, -122.42] }, $maxDistance: 1000 } } }
D. { location: { $near: { $geometry: { type: 'Point', coordinates: [-122.42, 37.77] }, $maxDistance: 1000 } } }

Solution

  1. Step 1: Identify correct coordinate order and operator

    Coordinates must be [longitude, latitude], so [-122.42, 37.77] is correct. The $near operator with $maxDistance finds points within distance.
  2. Step 2: Evaluate each option

    { location: { $near: { $geometry: { type: 'Point', coordinates: [-122.42, 37.77] }, $maxDistance: 1000 } } } uses correct coordinates and $near with $maxDistance 1000 meters (1 km). { location: { $geoWithin: { $centerSphere: [[-122.42, 37.77], 1] } } } uses $geoWithin with radius in radians, not meters. { location: { $nearSphere: { $geometry: { type: 'Point', coordinates: [37.77, -122.42] }, $maxDistance: 1000 } } } swaps coordinates. { location: { $near: { $geometry: { type: 'Point', coordinates: [-122.42, 37.77] }, $minDistance: 1000 } } } uses $minDistance which finds points farther than 1 km, not within.
  3. Final Answer:

    { location: { $near: { $geometry: { type: 'Point', coordinates: [-122.42, 37.77] }, $maxDistance: 1000 } } } -> Option D
  4. Quick Check:

    $near + $maxDistance + correct coords = find nearby points [OK]
Hint: Use $near with $maxDistance and correct coords for nearby search [OK]
Common Mistakes:
  • Swapping latitude and longitude
  • Using $minDistance instead of $maxDistance
  • Confusing meters with radians in $geoWithin
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard