📅  最后修改于: 2023-12-03 15:32:56.458000             🧑  作者: Mango
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.
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();
});
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");
});
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.
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.
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.