MongoDB $geoNear result separate distance from returned document

296 Views Asked by At

I am running a MongoDB query in .NET application that is using $geoNear aggregation stage and returns a list of object within a specified distance. It is returning them in following format (I am using results from MongoDB examples page for simplification):

{
   "_id" : 8,
   "name" : "Sara D. Roosevelt Park",
   "location" : {
      "type" : "Point",
      "coordinates" : [
         -73.9928,
         40.7193
      ]
   },
   "category" : "Parks",
   "distance" : 974.175764916902
}

which is essentially my output type with added "distance" field. What I want to do is separate them into a different class so it looks like this:

public class EventLocationSearchResult
{
    public Event Event { get; set; }
    public double Distance { get; set; }
}

My code so far looks like this:

var result = await events
          .Aggregate()
          .AppendStage(GeoHelper.GetGeoNearStage<Event>(lon, lat, distance))
          .Lookup<User, Event>(_usersCollectionName, "memberIds", "id", "Members")
          .ToListAsync();

with GeoHelper.GetGeoNearStage(..) looking like so:

public static BsonDocumentPipelineStageDefinition<TNewResult, TNewResult> GetGeoNearStage<TNewResult>(double lon, double lat, double distance, string dbField)
{
    var geoNearOptions = new BsonDocument
    {
        { "near", new GeoJsonPoint<GeoJson2DGeographicCoordinates>(new GeoJson2DGeographicCoordinates(lon, lat)).ToBsonDocument()},
        { "maxDistance", distance },
        { "distanceField", "Distance" },
        { "spherical", true }
    };

    var stage = new BsonDocumentPipelineStageDefinition<TNewResult, TNewResult>(new BsonDocument { { "$geoNear", geoNearOptions } });

    return stage;
}

can I do it somehow? Thanks for any help!

0

There are 0 best solutions below