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
]
}
}