使用C#(mongocsharpdriver)在MongoDB中查找不同的计数

使用C#(mongocsharpdriver)在MongoDB中查找不同的计数,c#,mongodb,mongodb-csharp-2.0,C#,Mongodb,Mongodb Csharp 2.0,我有一个MongoDB集合,我需要在运行过滤器后找到记录的不同计数。 这就是我现在所拥有的 var filter = Builders<Foo>.Filter.Eq("bar", "1"); db.GetCollection<Foo>("FooTable").Distinct<dynamic>("zoo", filter).ToList().Count; var filter=Builders.filter.Eq(“条”,“1”); db.GetCollec

我有一个MongoDB集合,我需要在运行过滤器后找到记录的不同计数。 这就是我现在所拥有的

var filter = Builders<Foo>.Filter.Eq("bar", "1");
db.GetCollection<Foo>("FooTable").Distinct<dynamic>("zoo", filter).ToList().Count;
var filter=Builders.filter.Eq(“条”,“1”);
db.GetCollection(“FooTable”).Distinct(“zoo”,filter).ToList().Count;
我不喜欢这个解决方案,因为它读取内存中的集合以获取计数


有没有更好的方法可以直接从数据库中获取不同的计数?

下面的代码将使用聚合框架完成这项工作

var x = db.GetCollection<Foo>("FooTable")
    .Aggregate()
    .Match(foo => foo.bar == 1)
    .Group(foo => foo.zoo,
           grouping => new { DoesNotMatter = grouping.Key })
    .Count()
    .First()
    .Count;
这将使用索引(如果可用),但是,是的,它将把所有不同值的列表传输回客户端

db.GetCollection<Foo>("FooTable").Distinct(d => d.zoo, d => d.bar == 1).ToList().Count;