2

I'm using Aggregation to do a query and lookup. What's the most efficient way of returning both the results and count using one server call?

I've seen there is a way to do this using Facets, however, I'd like to do this using a Fluent expression with typed classes so I can abstract the logic into a generic extension method.

My current code looks something like this:

collection
  .Aggregate ()
  .Match (Builders<Order>.Filter...)
  .Lookup (...)
  .Project<Order> (Builders<Order>.Projection.Exclude ...)
Graeme
  • 773
  • 1
  • 8
  • 18

1 Answers1

3

I believe you are looking for the $group operator.

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();

This will give you an anonymous object containing your count and results in one. I dont know how your entity looks so I have assumed some names but you should be able to infer from this.

cl0ud
  • 1,524
  • 11
  • 27