Case
I have store the location coordinates in MongoDB collection with 2dsphere index. I want to get the records which included into the specific bounds on map. I have one coordinate point which is fixed with latitude and longitude. I have used the method $geoWithin
with $box
in MongoDB aggregation. I am able to get the data properly.
Problem
I need to add distance field in each record from the one fixed latitude and longitude I have.
{
"$match": {
"location": {
"$geoWithin": {
"$box": [
[
0.024719919885622943,
51.54643953472475
],
[
-0.1589577534542408,
51.47239969138267
]
]
}
}
}
}
Now I have coordinates array-like [-0.0649729793707321, 51.50160291888072]
I need distance for each record from the above point. How can I find this distance field with MongoDB aggregation?
sample document for the database record
{
"_id" : ObjectId("5e342ac2e0dcfa65273751ea"),
"location" : {
"type" : "Point",
"coordinates" : [
-0.123507,
51.5083228
]
},
"status" : 1,
"price" : {
"value" : 27,
"type" : "day",
"base" : 3.38
},
"name" : "Initial Space with Wormup",
"venuePolicy" : "Venue Policies",
"updatedAt" : ISODate("2020-02-20T12:28:16.024Z"),
"createdAt" : ISODate("2020-01-31T13:25:22.600Z"),
"dimension" : {
"width" : 100
},
"description" : "<p>Hi, </p><p>please find attached document for testing purpose",
}