MongoDb : Aggregate method taking too long

I’m trying to perform a simple aggregation pipeline for Mongo DB using the C# driver. Here is my code :

internal async Task<IEnumerable<BsonDocument>> GetDocumentsAsync(string collectionName, int? pageIndex, int? pageSize) {
    var collection = _database.GetCollection<BsonDocument>(collectionName);

    var aggregationPipeline = new BsonDocument[]
        new BsonDocument("$skip", pageSize * (pageIndex ?? 0)),
        new BsonDocument("$limit", pageSize ?? 10)

    var result = await collection.Aggregate(aggregationPipeline).ToListAsync();

    return result; 

But the aggregate function takes ~7s.

I’ve tried the same code (with the same pipelines) but in node.js and it takes only 0.7s (10 times less).

The total count of documents in the collection is 30K. Why does it take so long using the C# driver ? Is there any way to fix this performance issue ?

Thank you

Hi, @ChaReborn,

Welcome to the MongoDB Community Forums. I understand that you are observing a 10x performance difference between the .NET/C# Driver and the Node.js Driver. Reviewing your C# code, I notice that you call ToListAsync which will not only execute the query, but also exhaustion of the cursor possibly requiring multiple roundtrips to the server to fetch all the 16MB batches. It will also deserialize the returned binary BSON returned on the wire into C# BsonDocument objects.

Without seeing your Node.js code it is hard to say whether your Node.js code is doing the same amount of work. Typical Node.js usage would be to return the result of Collection.aggregate, which is a cursor and not the deserialized results. You can achieve a similar result by calling ToCursorAsync() in your C# code. This will execute the query and return a cursor to the results that can be lazily iterated.

Please try ToCursorAsync in your C# code and see if you achieve similar performance results as your Node.js code.