Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDb Count after aggregation C# 2.0 driver

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

like image 343
Vladyslav Furdak Avatar asked Sep 14 '15 14:09

Vladyslav Furdak


People also ask

Can we use count with aggregate function in MongoDB?

The MongoDB $count operator allows us to pass a document to the next phase of the aggregation pipeline that contains a count of the documents. There a couple of important things to note about this syntax: First, we invoke the $count operator and then specify the string.

How do I count documents in MongoDB aggregation?

MongoDB aggregate $count queryIt transfers a document to the next stage that contains a count of the number of documents input to the stage. Here, the string is the name of the output field which has the count as its value. And, the string must be a non-empty string, not start with '$' and not contain '. ' character.

How do I count fields in MongoDB?

First stage $project is to turn all keys into array to count fields. Second stage $group is to sum the number of keys/fields in the collection, also the number of documents processed. Third stage $project is subtracting the total number of fields with the total number of documents (As you don't want to count for _id ).

Is count faster than find MongoDB?

find({}). count() more fast then collection.


1 Answers

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").
like image 175
Alex Krupka Avatar answered Sep 30 '22 19:09

Alex Krupka