Search code examples
c#mongodbmongodb-.net-drivermongodb-csharp-2.0

MongoDb c# 2.0 driver - how can i calculate count of aggregations on server?


When i ran dbCollection.Aggregate().Group(groupby).Match(query) I haven't any extention method to get a count of records what was aggregated. But i can run ToListAsync and then get Count(). How can i receive a count of records ? I have MongoDb v 3.0.2 and c# driver 2.0


Solution

  • You should add one more group with $sum

    var result = await collection
            .Aggregate()
            .Group(groupby)
            .Match(query)
            .Group(new BsonDocument
            {
                { "_id", "_id" },
                {"count", new BsonDocument("$sum", 1)}
            })
            .FirstAsync();
            var count = result["count"].AsInt32;