Filter documents based on distance

I have 2 collections, Users and Events:

User example:

{
  location: {
    type: "Point",
    coordinates: [10, 20]
  },
  ...
}

Event example:

{
  location: {
    type: "Point",
    coordinates: [10, 50]
  },
  proximity: 10
  ...
}

Now, I want to find all Events related to a specific User, which means I should calculate distance between User’s and Event’s location, and check if that distance is lower than Event’s proximity property.

Note: I have User’s location as input, so I should only create a filter for Events.

I can easily do it if I would know how to calculate the distance between two geolocation points, but I could not find any operator in the docs that does it. How that can be calculated?

Hi @NeNaD,

You are looking for $near which will require a 2dsphere index.

Cheers,
Maxime.

Hi @MaBeuLux88,

Thanks for the answer! :smiley:

I already checked both $near and geoWithin (I don’t need sorting), but for some reason, it does not work.

Note that I have to use aggregate since the $radius/$maxDistance need to be fetched from the proximity field on document level.

Can you please check this post and let me know what do you think?