Antes de comenzar, asegúrate de tener lo siguiente instalado:
1. Node.js: JavaScript runtime que permite ejecutar código JavaScript del lado del servidor.
2. MongoDB: Base de datos NoSQL.
3. MongoDB Node.js Driver: Cliente que permite interactuar con MongoDB desde Node.js.
Primero, asegúrate de tener MongoDB en funcionamiento. Puedes usar una instancia local o una en la nube como MongoDB Atlas.
En tu proyecto Node.js, instala el paquete de MongoDB utilizando npm:
npm install mongodb
Crea un archivo app.js
y configura la conexión a MongoDB:
const { MongoClient } = require('mongodb');
async function main() {
const uri = 'your_mongodb_connection_string';
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
console.log('Connected to MongoDB');
} catch (e) {
console.error(e);
} finally {
await client.close();
}
}
main().catch(console.error);
Reemplaza 'your_mongodb_connection_string'
con tu cadena de conexión de MongoDB.
Para realizar búsquedas geoespaciales, tus documentos deben tener datos de coordenadas. MongoDB utiliza el tipo de datos GeoJSON
para almacenar coordenadas.
{
"name": "Central Park",
"location": {
"type": "Point",
"coordinates": [-73.965355, 40.782865]
}
}
Añadamos algunos documentos de ejemplo a nuestra base de datos:
async function insertLocations(client) {
const collection = client.db('geo_example').collection('locations');
const locations = [
{
name: "Central Park",
location: {
type: "Point",
coordinates: [-73.965355, 40.782865]
}
},
{
name: "Empire State Building",
location: {
type: "Point",
coordinates: [-73.985656, 40.748817]
}
},
{
name: "Statue of Liberty",
location: {
type: "Point",
coordinates: [-74.044502, 40.689247]
}
}
];
await collection.insertMany(locations);
console.log('Locations inserted');
}
async function main() {
const uri = 'your_mongodb_connection_string';
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
await insertLocations(client);
} catch (e) {
console.error(e);
} finally {
await client.close();
}
}
main().catch(console.error);
Para realizar búsquedas eficientes, es importante crear un índice geoespacial en el campo que contiene las coordenadas.
async function createIndex(client) {
const collection = client.db('geo_example').collection('locations');
await collection.createIndex({ location: '2dsphere' });
console.log('2dsphere index created');
}
async function main() {
const uri = 'your_mongodb_connection_string';
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
await createIndex(client);
} catch (e) {
console.error(e);
} finally {
await client.close();
}
}
main().catch(console.error);
MongoDB proporciona varias maneras de realizar consultas geoespaciales, como la búsqueda de puntos cercanos, la búsqueda dentro de un área, y más. Vamos a explorar algunas de ellas.
Para encontrar los documentos más cercanos a un punto específico, puedes usar la operación $near
:
async function findNearbyLocations(client, longitude, latitude, maxDistance) {
const collection = client.db('geo_example').collection('locations');
const query = {
location: {
$near: {
$geometry: {
type: "Point",
coordinates: [longitude, latitude]
},
$maxDistance: maxDistance // Distancia máxima en metros
}
}
};
const locations = await collection.find(query).toArray();
console.log('Nearby locations:', locations);
}
async function main() {
const uri = 'your_mongodb_connection_string';
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
await findNearbyLocations(client, -73.985656, 40.748817, 5000); // Ejemplo: Buscar cerca del Empire State Building en un radio de 5km
} catch (e) {
console.error(e);
} finally {
await client.close();
}
}
main().catch(console.error);
Para encontrar documentos dentro de un área específica, puedes usar la operación $geoWithin
. Por ejemplo, para buscar dentro de un polígono:
async function findLocationsInPolygon(client) {
const collection = client.db('geo_example').collection('locations');
const polygon = {
type: "Polygon",
coordinates: [[
[-74.047285, 40.683927],
[-73.910408, 40.877483],
[-73.856077, 40.775002],
[-74.047285, 40.683927]
]]
};
const query = {
location: {
$geoWithin: {
$geometry: polygon
}
}
};
const locations = await collection.find(query).toArray();
console.log('Locations within polygon:', locations);
}
async function main() {
const uri = 'your_mongodb_connection_string';
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
await findLocationsInPolygon(client);
} catch (e) {
console.error(e);
} finally {
await client.close();
}
}
main().catch(console.error);
En este artículo, hemos cubierto cómo realizar búsquedas basadas en coordenadas en MongoDB utilizando JavaScript. Hemos visto cómo insertar documentos con coordenadas geoespaciales, crear índices geoespaciales y realizar búsquedas de puntos cercanos y dentro de áreas específicas. MongoDB ofrece un poderoso conjunto de herramientas para trabajar con datos geoespaciales, permitiendo construir aplicaciones robustas y eficientes.
Jorge García
Fullstack developer