📜  mongodb distancefield to kms - Javascript (1)

📅  最后修改于: 2023-12-03 15:32:56.458000             🧑  作者: Mango

MongoDB distanceField to KMs - JavaScript

MongoDB is a document-oriented NoSQL database used for high-volume data storage. One of its features is the ability to perform geospatial queries. In this tutorial, we will explore how to use the distanceField operator in MongoDB to convert distance values from meters to kilometers using JavaScript.

Prerequisites
  • Node.js installed on your system
  • MongoDB Atlas account (for cloud-based deployments) or MongoDB Community Server installed
  • Basic knowledge of MongoDB queries and aggregation pipeline
Steps
  1. Connect to your MongoDB server and create a database using Node.js:
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb://localhost:27017/mydb";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
  const collection = client.db("mydb").collection("mycollection");
  // perform operations using the collection object
  client.close();
});
  1. Insert sample data into the collection. For this tutorial, we will use a collection of airports, containing the airport name, location (latitude and longitude), and altitude.
const airports = [
  { "name": "JFK International Airport", "location": { "type": "Point", "coordinates": [-73.7781, 40.6413] }, "altitude": 13 },
  { "name": "Heathrow Airport", "location": { "type": "Point", "coordinates": [-0.461941, 51.4706] }, "altitude": 25 },
  { "name": "Changshui International Airport", "location": { "type": "Point", "coordinates": [102.9289, 25.1001] }, "altitude": 2160 },
  { "name": "Singapore Changi Airport", "location": { "type": "Point", "coordinates": [103.9872, 1.3644] }, "altitude": 7 },
  { "name": "Sydney Kingsford Smith Airport", "location": { "type": "Point", "coordinates": [151.1818, -33.9461] }, "altitude": 6 }
];

collection.insertMany(airports, function(err, res) {
  console.log("Documents inserted successfully");
});
  1. Use the $geoNear operator to perform a geospatial query on the collection. The query matches all airports within a certain distance of a given point:
collection.aggregate([
  {
    $geoNear: {
       near: { type: "Point", coordinates: [ -73.9667, 40.78 ] },
       distanceField: "distance",
       spherical: true,
       maxDistance: 100000
    }
  }
]).toArray(function(err, result) {
  console.log(result);
});

In this example, we are searching for airports within 100 kilometers of the point (-73.9667, 40.78) using the $geoNear operator. The result is an array of documents that match the query criteria.

  1. Use the $addFields operator to add a new field to the result set that contains the distance in kilometers. The result is an updated array of documents that includes the new field:
collection.aggregate([
  {
    $geoNear: {
       near: { type: "Point", coordinates: [ -73.9667, 40.78 ] },
       distanceField: "distance",
       spherical: true,
       maxDistance: 100000
    }
  },
  {
    $addFields: {
      distanceKM: { $divide: [ "$distance", 1000 ] }
    }
  }
]).toArray(function(err, result) {
  console.log(result);
});

In this example, we are using the $addFields operator to add a new field called "distanceKM" to the result set. The $divide operator is used to convert the "distance" field from meters to kilometers.

Conclusion

In this tutorial, we learned how to use the distanceField operator in MongoDB to convert distance values from meters to kilometers using JavaScript. We also explored how to perform geospatial queries using the $geoNear operator. With these tools, you can build powerful location-based applications that use MongoDB as the backend database.