Geospatial queries basics in MongoDB - Time & Space Complexity
When we use geospatial queries in MongoDB, we want to find locations near a point or within an area.
We ask: How does the time to find these locations grow as we have more places stored?
Analyze the time complexity of the following geospatial query.
db.places.createIndex({ location: "2dsphere" })
const nearbyPlaces = db.places.find({
location: {
$near: {
$geometry: { type: "Point", coordinates: [ -73.97, 40.77 ] },
$maxDistance: 5000
}
}
})
This code finds places within 5 kilometers of a given point using a 2dsphere index.
Look for repeated work done by the query.
- Primary operation: Searching the geospatial index to find matching locations.
- How many times: The index search visits parts of the tree structure depending on data size and query area.
As we add more places, the search looks through more index nodes but not every place.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 3-5 index checks |
| 100 | About 7-10 index checks |
| 1000 | About 10-15 index checks |
Pattern observation: The search grows slowly, checking only parts of the index, not every place.
Time Complexity: O(log n)
This means the query time grows slowly as the number of places grows, thanks to the index.
[X] Wrong: "The query checks every place one by one, so it takes longer linearly as data grows."
[OK] Correct: The 2dsphere index lets MongoDB skip many places, searching efficiently like a tree, not a list.
Understanding how geospatial queries scale shows you know how databases handle location data efficiently.
"What if we removed the 2dsphere index? How would the time complexity change?"
Practice
$near operator do in MongoDB geospatial queries?Solution
Step 1: Understand the purpose of
The$near$nearoperator is used to find documents that are geographically close to a given point.Step 2: Compare options with
Only Finds documents with locations closest to a specified point correctly describes finding documents near a location. Other options describe unrelated actions.$nearfunctionalityFinal Answer:
Finds documents with locations closest to a specified point -> Option AQuick Check:
$near= Finds nearby points [OK]
- Thinking $near deletes or updates documents
- Confusing $near with sorting operators
- Assuming $near works without a geospatial index
$near in MongoDB?Solution
Step 1: Recall coordinate order in MongoDB
Coordinates must be in [longitude, latitude] order, so longitude comes first.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.Final Answer:
{ location: { $near: { $geometry: { type: 'Point', coordinates: [-70, 40] } } } } -> Option AQuick Check:
Coordinates = [longitude, latitude] [OK]
- Swapping latitude and longitude order
- Using positive latitude as longitude
- Forgetting to use $geometry inside $near
location, what will this query return?{ location: { $near: { $geometry: { type: 'Point', coordinates: [-73.97, 40.77] }, $maxDistance: 500 } } }Solution
Step 1: Understand $near with $maxDistance
The query finds documents near the point within the maximum distance specified (500 meters).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.Final Answer:
Documents with locations within 500 meters of [-73.97, 40.77] -> Option BQuick Check:
$near + $maxDistance = nearby points within distance [OK]
- Thinking $maxDistance means exact match
- Assuming it returns points beyond maxDistance
- Ignoring the need for a 2dsphere index
{ location: { $near: { $geometry: { type: 'Point', coordinates: [40.77, -73.97] } } } }What is the most likely cause?
Solution
Step 1: Requirements for $near with $geometry
The$nearoperator with$geometryrequires a 2dsphere index on thelocationfield.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.Final Answer:
Thelocationfield is not indexed with 2dsphere -> Option CQuick Check:
$near requires 2dsphere index [OK]
- Swapping latitude and longitude
- Assuming $maxDistance is required
- Confusing geometry types
{ type: 'Point', coordinates: [-122.42, 37.77] }. Which query correctly finds these restaurants assuming a 2dsphere index on location?Solution
Step 1: Identify correct coordinate order and operator
Coordinates must be [longitude, latitude], so [-122.42, 37.77] is correct. The$nearoperator with$maxDistancefinds points within distance.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.Final Answer:
{ location: { $near: { $geometry: { type: 'Point', coordinates: [-122.42, 37.77] }, $maxDistance: 1000 } } } -> Option DQuick Check:
$near + $maxDistance + correct coords = find nearby points [OK]
- Swapping latitude and longitude
- Using $minDistance instead of $maxDistance
- Confusing meters with radians in $geoWithin
Ready to prove it?
Pass the test and this pattern moves unknown
