Skip to content

Instantly share code, notes, and snippets.

@searock
Created July 12, 2018 23:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save searock/ce7d221b00789ae6c8ee69b7f56ed90c to your computer and use it in GitHub Desktop.
Save searock/ce7d221b00789ae6c8ee69b7f56ed90c to your computer and use it in GitHub Desktop.
Querying origin and destination location in mongoDB
//class
var package = function (packageName, originLatitude, originLongitude,
destinationLatitude, destinationLongitude) {
return {
packageName : packageName,
origin : { type : "Point", coordinates: [originLatitude, originLongitude]},
destination : { type : "Point", coordinates: [destinationLatitude, destinationLongitude]}
};
};
//function
var addNewPackage = function(packageName, originLatitude, originLongitude,
destinationLatitude, destinationLongitude){
db.locations.insert(package(packageName, originLatitude, originLongitude,
destinationLatitude, destinationLongitude));
};
//add values
addNewPackage("laptop", -41.4715662, -72.9438304,
-41.4876745, -72.8901151);
addNewPackage("mobile", -41.4675677, -72.9510547,
-41.4876745, -72.8901151);
addNewPackage("xbox one", -33.453278, -70.5729207,
-33.4545361, -70.6032303);
addNewPackage("ps4", -33.4378439, -70.6526683,
-33.4529326, -70.6689274);
addNewPackage("tv", -33.442691, -70.6479087,
-33.4639951, -70.6536594);
//query (search in 1km radius)
db.locations.find(
{
origin: {
$geoWithin: {
$center: [ [ -41.4736726,-72.9478899 ] , 1]
}
},
destination: {
$geoWithin: {
$center: [ [ -41.4876745,-72.8923038 ] , 1]
}
}
}
).pretty()
//result
{
"_id" : ObjectId("5b47e2c27385fd527f4bc6e1"),
"packageName" : "laptop",
"origin" : {
"type" : "Point",
"coordinates" : [
-41.4715662,
-72.9438304
]
},
"destination" : {
"type" : "Point",
"coordinates" : [
-41.4876745,
-72.8901151
]
}
}
{
"_id" : ObjectId("5b47e2c27385fd527f4bc6e2"),
"packageName" : "mobile",
"origin" : {
"type" : "Point",
"coordinates" : [
-41.4675677,
-72.9510547
]
},
"destination" : {
"type" : "Point",
"coordinates" : [
-41.4876745,
-72.8901151
]
}
}
@searock
Copy link
Author

searock commented Jul 12, 2018

mongoDB is one of the best database that supports geo coordinates. This example shows how you can search for origin and destination from a collection.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment