{"success":true,"name":"use-mongodb-2dsphere-indexes-for-location-features-not-manua","description":"Building 'near me' or map features over MongoDB location data","category":"ai-brimind","path":"ai-brimind/use-mongodb-2dsphere-indexes-for-location-features-not-manua/SKILL.md","file":"SKILL.md","content":"---\nname: use-mongodb-2dsphere-indexes-for-location-features-not-manua\ndescription: \"Building 'near me' or map features over MongoDB location data\"\n---\n\n# Use MongoDB 2dsphere Indexes for Location Features, Not Manual Math\n\n## When to use\nProject uses MongoDB, and the app must find documents by distance, radius, or area (stores near a user, points on a map).\n\n## Example request\nFetching all docs and computing distance in JS → $near with a 2dsphere index does it in the database, sorted by distance. Storing location as { lat, lng } → GeoJSON demands { type: 'Point', coordinates: [lng, lat] } — longitude FIRST; the classic silent bug. 'Within this city area' queries → $geoWithin with a polygon is the built-in; no bounding-box hand-math. $near erroring 'unable to find index' → geo operators REQUIRE the 2dsphere index; it's not an optimization, it's a prerequisite. Each maps to 'geospatial is a solved subsystem — store GeoJSON, index 2dsphere, query with geo operators'.\n\n## Instructions\nAct as a developer who recognizes 'find things near a point' as a solved database feature before writing any distance formula. When location queries appear on MongoDB: (1) store locations in GeoJSON format — { type: 'Point', coordinates: [longitude, latitude] } — and burn in the trap: coordinates are [lng, lat], the reverse of how humans say it; a swap produces results that look plausible and are wrong, (2) create the 2dsphere index on the location field FIRST — geo operators like $near don't merely run slow without it, they refuse to run, (3) map the need to the built-in operator: $near / $nearSphere for distance-sorted 'near me' (with maxDistance in meters), $geoWithin for 'inside this area/polygon/radius', $geoIntersects for shape overlap, and $geoNear as the aggregation stage when the pipeline needs the computed distance as a field, (4) never fetch-all-and-filter-in-JS — that's reimplementing the index at application speed, (5) validate incoming coordinates at the boundary (ranges: lng −180..180, lat −90..90) since one corrupted point can break index builds. If the precision or radius requirements are vague, ask. Only ship the feature once the index exists and a known location returns at a sane distance in a real test, and explain why the database — not the app — is doing the geometry.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #1160\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}