使用 C# 驱动程序获取 MongoDb 结果和聚合计数

问题描述 投票:0回答:2

我正在使用聚合来进行查询和查找。使用一次服务器调用返回结果和计数的最有效方法是什么?

我已经看到有一种方法可以做到这一点使用 Facets,但是,我想使用具有类型化类的 Fluent 表达式来做到这一点,这样我就可以将逻辑抽象为通用扩展方法。

我当前的代码看起来像这样:

collection
  .Aggregate ()
  .Match (Builders<Order>.Filter...)
  .Lookup (...)
  .Project<Order> (Builders<Order>.Projection.Exclude ...)
mongodb mongodb-.net-driver mongodb-csharp-2.0
2个回答
3
投票

我相信您正在寻找 $group 运算符。

collection
.Aggregate ()
.Match (Builders<Order>.Filter...)
.Lookup (...)
.Project<Order> (Builders<Order>.Projection.Exclude ...)
.Group(x => x.OrderId, g => new { ResultCount = g.Count(), Data = g.Select(x => new Order { SomeOrderProperty = x.AnotherOne}).ToList() }).FirstOrDefault();

这将为您提供一个匿名对象,其中包含您的计数和结果。我不知道你的实体看起来如何,所以我假设了一些名称,但你应该能够从中推断出来。


0
投票

上面的答案将返回总数,但只返回 1 个搜索结果,这是不正确的。

在浏览 C# 驱动程序的源代码和单元测试时,我能够构建正确的查询来获得限制为 20 的搜索结果,并获得该搜索查询在服务器上的文档总数。

            var result = await collection.Aggregate()
                        .Search(Builders<Product>.Search.Wildcard(g => g.Name, searchText),
                                indexName: "products",
                                count: new MongoDB.Driver.Search.SearchCountOptions { Type = MongoDB.Driver.Search.SearchCountType.Total })
                        .Project<Product>(Builders<Product>.Projection
                            .SearchMeta(x => x.MetaResult)
                                .Include(p => p.Name))
                        .Limit(1).SortBy(p => p.Name)
                                .ToListAsync(cancellationToken: cancellationToken);

这对应于以下 Mongo 管道表达式:

[
  {
    $search: {
      wildcard: {
        query: "sunshine",
        path: "name",
      },
      count: { type: "total" },
      index: "products",
    },
  },
  {
    $project: {
      metaResult: "$$SEARCH_META",
      name: 1,
    },
  },
  { $limit: NumberLong(1) },
  { $sort: { name: 1 } },
]
© www.soinside.com 2019 - 2024. All rights reserved.