0
0
MongoDBquery~30 mins

Geospatial queries basics in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Geospatial Queries Basics with MongoDB
📖 Scenario: You are building a simple location-based service that stores places with their geographic coordinates. You want to find places near a specific location.
🎯 Goal: Create a MongoDB collection with place data including coordinates, set up a geospatial index, and write a query to find places near a given point.
📋 What You'll Learn
Create a MongoDB collection named places with documents containing name and location fields.
The location field must be a GeoJSON point with exact coordinates.
Create a 2dsphere index on the location field.
Write a query using $near to find places near a specific coordinate.
💡 Why This Matters
🌍 Real World
Location-based services like finding nearby restaurants, parks, or stores use geospatial queries to provide relevant results based on user location.
💼 Career
Understanding geospatial queries is important for roles involving location data, such as backend developers, data engineers, and GIS specialists.
Progress0 / 4 steps
1
Create the places collection with place documents
Insert three documents into the places collection with these exact entries: { name: "Central Park", location: { type: "Point", coordinates: [-73.9654, 40.7829] } }, { name: "Times Square", location: { type: "Point", coordinates: [-73.9855, 40.7580] } }, and { name: "Empire State Building", location: { type: "Point", coordinates: [-73.9857, 40.7484] } }.
MongoDB
Need a hint?

Use db.places.insertMany([...]) with the exact documents.

2
Create a 2dsphere index on the location field
Create a geospatial index on the location field of the places collection using db.places.createIndex({ location: "2dsphere" }).
MongoDB
Need a hint?

Use db.places.createIndex({ location: "2dsphere" }) to enable geospatial queries.

3
Write a query to find places near a specific point
Write a query to find places near the coordinate [-73.9850, 40.7589] using db.places.find({ location: { $near: { $geometry: { type: "Point", coordinates: [-73.9850, 40.7589] } } } }).
MongoDB
Need a hint?

Use db.places.find({ location: { $near: { $geometry: { type: "Point", coordinates: [...] } } }) with the exact coordinates.

4
Assign the query result to a variable to complete the setup
Assign the result of the db.places.find query to a variable named nearbyPlaces to complete the geospatial query setup.
MongoDB
Need a hint?

Assign the query to nearbyPlaces using const nearbyPlaces = db.places.find(...).