Linked Questions

Popular Questions

I have a collection that has an array of geo_json objects which looks like below:

{
   id: 1,
   title: 'test',
   description: 'test',
   locations: [
      {
         geo_json: {
            type: 'Point',
            coordinates: [121.21, 14.58]
         }
      },
      {
         geo_json: {
            type: 'Point',
            coordinates: [111.11, 10.28]
         }
      }
   ]
}

I have a 2DSphere index on that field, and my query looks like this:

query = {
            'locations.geo_json': {
                '$near': {
                    '$geometry': {
                        'type': 'Point',
                        'coordinates': [lng, lat]
                    },
                    '$maxDistance': 5000
                }
            }
        }

It does what is supposed to do, which is, giving back the collection items that are within the designated radius (max distance), my problem is, I want to return only the actual point in the array that is "near" the coordinates specified, not the whole array of locations.

So for example, like the above, if I query with lat=14.58, lng=121.21, I'll get the item with id=1, but in the locations field I only need the matching location there, which is [121.21, 14.58] and not including [111.11, 10.28].

So it will return like this:

{
   id: 1,
   title: 'test',
   description: 'test',
   locations: [
      {
         geo_json: {
            type: 'Point',
            coordinates: [121.21, 14.58]
         }
      }
   ]
}

This is will help in plotting items that surround the point queried.

Hope someone can help :)

Related Questions