Search code examples
c#mongodbaggregation-frameworkmongodb-.net-driver

How to use MongoDB Compass' generated pipeline in C# to run aggregation pipeline


I used MongoDB's Compass to created a pipeline that I exported to C#, however I am not sure how to use this (tool generates a BsonArray) in the actual code to perform an aggregation? This is a geoNear which isn't currently supported by LINQ, if that has any bearing.

I attempted to use this var result = collection.Aggregate(pipeline); which some documentation suggested (pipeline - is that BsonArray object generated by Compass.

Example of what compass would create:

new BsonArray
{
    new BsonDocument("$geoNear",
    new BsonDocument
        {
            { "near",
    new BsonDocument
            {
                { "type", "Point" },
                { "coordinates",
    new BsonArray
                {
                    -2.11,
                    52.55
                } }
            } },
            { "distanceField", "distanceField" },
            { "maxDistance", 5000 },
            { "spherical", true }
        }),
    new BsonDocument("$sort",
    new BsonDocument("distanceField", -1))
};

Solution

  • Turns out that using the compass generated code just needed to be strongly typed. For some reason the compiler could not interpret what was going on (contrary to original code idea. So instead of using var a type was required. Seems so trivial now...

    so as an example:

     PipelineDefinition<Transport, Transport> pipeline= new BsonArray
        {
            new BsonDocument("$geoNear",
            new BsonDocument
                {
                    { "near",
            new BsonDocument
                    {
                        { "type", "Point" },
                        { "coordinates",
            new BsonArray
                        {
                            -2.11,
                            52.55
                        } }
                    } },
                    { "distanceField", "distanceField" },
                    { "maxDistance", 5000 },
                    { "spherical", true }
                }),
            new BsonDocument("$sort",
            new BsonDocument("distanceField", -1))
        };
    
    
     //this will now work
     var cursor = await collection.AggregateAsync(pipeline);
     var listResult = await cursor.ToListAsync();