1. Explain geospatial indexes in MongoDB. What are the differences between 2d and 2dsphere indexes?
Geospatial indexes in MongoDB enable efficient queries on location data, allowing you to find documents based on geographic coordinates. MongoDB supports two types of geospatial indexes: 2d for flat geometries and 2dsphere for spherical geometries. 2d indexes are designed for flat, two-dimensional coordinate systems like maps. They work with legacy coordinate pairs represented as arrays of two numbers. 2d indexes support queries within rectangles, circles, and polygons on a flat plane. Use 2d indexes when your data represents points on a flat map, such as game positions or floor plans. 2dsphere indexes work with spherical geometries that model the Earth's surface. They use GeoJSON format to represent points, lines, and polygons considering the Earth as an oblate spheroid. This provides accurate distance calculations for geographic coordinates like GPS locations. 2dsphere indexes support queries like finding locations within a certain distance, within a polygon, or along a route. GeoJSON format specifies geometry types and coordinates. A point is defined with type Point and coordinates as longitude then latitude. A polygon is defined with type Polygon and an array of coordinate arrays forming closed rings. MongoDB provides geospatial query operators like dollar near for proximity queries, dollar geoWithin for area queries, and dollar geoIntersects for intersection queries. Geospatial queries are essential for location-based applications like finding nearby restaurants, delivery routing, ride-sharing services, or real estate searches. The 2dsphere index is recommended for most geographic applications because it accounts for the Earth's curvature and provides more accurate results.