9

I have the following aggregation pipline

var count = dbCollection.
Aggregate(new AggregateOptions { AllowDiskUse = true }).Match(query).
Group(groupby).
ToListAsync().Result.Count();

And this gets the following result:

{
    "result" : [ 
        {
            "_id" : {
                "ProfileId" : ObjectId("55f6c727965bb016c81971ba")
            }
        }, 
        {
            "_id" : {
                "ProfileId" : ObjectId("55f6c727965bb016c81971bb")
            }
        }
    ],
    "ok" : 1
}

But it seems it will make count operation on client, but how to perform it in MongoDb ? I have MongoDb 2.0 C# driver & MongoDb v. 3.0.2

Vladyslav Furdak
  • 1,765
  • 2
  • 22
  • 46
  • https://docs.mongodb.org/getting-started/csharp/aggregation/#group-documents-by-a-field-and-calculate-count – ThrowsException Sep 15 '15 at 00:16
  • 1
    @ThrowsException the OP needs to count the number of results, not the counts for each _id – Mario Trucco Sep 17 '15 at 15:27
  • 1
    Can you give an example of your collection, and explain exactly what you want to count? I am not clear on the goal of your query. Also, please add the query and the groupby statements to the question. – agarcian Sep 18 '15 at 18:31

1 Answers1

6

Add a constant field to your group function and then group again on the constant field (so that all the results are grouped into a single group) with a aggregate sum of 1. The first (and only) result will have the sum.

Ex.

var count = dbCollection.
Aggregate(new AggregateOptions { AllowDiskUse = true }).Match(query).
Group(groupby).Group(<id>:{ConstantField},Total:{$sum:1})
ToListAsync().Result.First().GetValue("Total").
Alex Krupka
  • 710
  • 9
  • 20