0

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!

Marcin Bator
  • 341
  • 1
  • 8
  • 23
  • Do you just need a Project stage? – Kevin Smith Apr 01 '20 at 21:15
  • @KevinSmith could you elaborate? How could project stage help me? – Marcin Bator Apr 01 '20 at 21:33
  • From my understanding, you want to get the object you described from the result set after the `Lookup` stage? Or maybe I'm not fully understanding your question – Kevin Smith Apr 01 '20 at 21:36
  • What I'm getting out of my current query is all fields of `Event` objects and a 'Distance' object. What I want to have as an output is an instance of the 'EventLocationSearchResult' type which contains a 'Event' object (this is all fields apart from 'Distance') and Distance field – Marcin Bator Apr 01 '20 at 21:39
  • What is the `.Lookup(_usersCollectionName, "memberIds", "id", "Members")` about in your example if you only want the event and distance> – Kevin Smith Apr 06 '20 at 09:07
  • Event includes its members that are stored in Users collection – Marcin Bator Apr 09 '20 at 12:24

0 Answers0