NeNaD
(Nenad Milosavljevic)
July 4, 2022, 9:53am
1
If we know longitude and latitude of the geolocation points, how we can calculate the distance between them?
For example, image this input document:
[
{
"location_1": {
"type": "Point",
"coordinates": [
10,
20
]
},
"location_2": {
"type": "Point",
"coordinates": [
10,
30
]
}
}
]
How can we calculate the distance between location_1
and location_2
?
Hi @NeNaD ,
Would the distance calculated with distance = ā ((x2-x1)Ā² + (y2-y1)Ā²)
work for you?
> db.coll.findOne()
{
_id: ObjectId("62c43a4128c8b27fda436536"),
location_1: { type: 'Point', coordinates: [ 10, 20 ] },
location_2: { type: 'Point', coordinates: [ 10, 30 ] }
}
Aggregation:
[
{
'$addFields': {
'distance': {
'$sqrt': {
'$add': [
{
'$pow': [
{
'$subtract': [
{
'$arrayElemAt': [
'$location_2.coordinates', 0
]
}, {
'$arrayElemAt': [
'$location_1.coordinates', 0
]
}
]
}, 2
]
}, {
'$pow': [
{
'$subtract': [
{
'$arrayElemAt': [
'$location_2.coordinates', 1
]
}, {
'$arrayElemAt': [
'$location_1.coordinates', 1
]
}
]
}, 2
]
}
]
}
}
}
}
]
Result:
[
{
_id: ObjectId("62c43a4128c8b27fda436536"),
location_1: { type: 'Point', coordinates: [ 10, 20 ] },
location_2: { type: 'Point', coordinates: [ 10, 30 ] },
distance: 10
}
]
Cheers,
Maxime.
1 Like
NeNaD
(Nenad Milosavljevic)
July 5, 2022, 9:52pm
3
Hi @MaBeuLux88_xxx ,
Thanks for the response!
Actually, it should be calculated like in this SO answer here .
I just though that maybe I can use some built-in operator for that. Can you tell me where I can submit a proposal for new operators?
I was actually afraid you would say something like that!
Well this calculation can also be done as their is also $cos, $sin, etc in the trigonometry operators . But my formula is probably good enough if you have all your points within the same city for example.
If this operator exists, I never heard of it.
Feedback & improvements are in this direction though and I like the idea! I would have also liked to find the ā$distanceā one that I had to āimplementā in hereā¦
https://feedback.mongodb.com/
Cheers,
Maxime.
NeNaD
(Nenad Milosavljevic)
July 6, 2022, 5:01am
5
Yeah, it would be great to have both of these built-in with some operator. Let me submit both suggestions!
NeNaD
(Nenad Milosavljevic)
July 6, 2022, 5:08am
6
Submitted.
Here is the suggestion , so everyone that would love to see these operators built-in can go and upvote the suggestion.
2 Likes
Looks like itās already in the backlog actually:
https://jira.mongodb.org/browse/SERVER-2990
I added my vote on it!
1 Like
system
(system)
Closed
July 11, 2022, 3:19pm
8
This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.