The answer above will return the total count but only 1 search result which is not correct.
While browsing the source code of the C# driver v2.22 and the unit tests, I was able to construct the correct query to get both the limited search result to 20 and also get the total count of documents at the server for this search query.
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);
this corresponds to the following Mongo pipeline expression:
[
{
$search: {
wildcard: {
query: "sunshine",
path: "name",
},
count: { type: "total" },
index: "products",
},
},
{
$project: {
metaResult: "$$SEARCH_META",
name: 1,
},
},
{ $limit: NumberLong(1) },
{ $sort: { name: 1 } },
]
You would need to add the SearchMetaResult.cs
to the Product class so that the deserializer correctly maps the additional count meta data.