Query by location when radius is declared in queried documents

I have 2 collections - one for user and other for blog. User has a location field and Blog has location and publishRadius fields. The publishRadius field is manually set for each blog by their authors to allow readers only from that circle to access the blog.
For each user, I want to find a list of blogs which can be served in the user’s location - kind of a reverse lookup.

I am very new to MongoDB but all the examples I have found so far are passing a static value in the maxDistance parameter of geospatial queries. Since the radius value is specific to each Blog document, I don’t have a number to pass upfront. Have I messed up the database design, or is there a solution to this?

Hi @dpux,
see this: node.js - Mongoose geolocation dynamic max distance - Stack Overflow
In your case it should be something like this:

    $geoNear: {
      near: userLocation,
      distanceField: "dist.calculated",
      spherical: true
    $match: {
      $expr: {
        $gt: ['$publishRadius', '$dist.calculated']


Thank you @Rafael_Green ! I haven’t tested the solution yet, but it’s relieving to know I won’t have to change my document structure :slight_smile:

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.