I am having some issues attempting some new count logic with the C# driver and the grouping function.
I used to use(simplified for forum):
collection.Aggregate().Match(filter).Group("{ _id: '" + "$" + distinctOn + "' }").Count().ToList()
This worked! Cool no problem. Now I am trying to use atlas search for the simple “filter” does not cut it any longer. No big deal so far, I switched to this.
PipelineDefinition<T, T> aPipeline = new List<BsonDocument>();
var coll = DB.GetCollection<T>(collectionName);
bool textSearchExists = MongoDBCommunicator.SearchIndexExists<T>(
DB, queryObject.TextSearch?.IndexName);
if (textSearchExists)
{
var buildBson = MongoDBCommunicator.BuildSearchPipeline<T>(
queryObject);
aPipeline = aPipeline.AppendStage(new BsonDocumentPipelineStageDefinition<T, T>(buildBson));
}
else
{
aPipeline = aPipeline.AppendStage(PipelineStageDefinitionBuilder.Match<T>(
filter ?? FilterDefinition<T>.Empty));
}
if (!string.IsNullOrEmpty(distinctOn))
{
aPipeline = aPipeline.AppendStage(new BsonDocumentPipelineStageDefinition<T, T>(
new BsonDocument("$group",
new BsonDocument
{
{ "_id", "$" + distinctOn },
{ "Item",
new BsonDocument("$first", "$$ROOT") }
})));
}
//aPipeline = aPipeline.AppendStage(new BsonDocumentPipelineStageDefinition<T, T>(
// new BsonDocument("$count", "'TotalCount'")));
You’ll notice the commented out Count Section at the bottom. This code does return the correct items, so I can iterate over the cursor and .Count myself, and I could make this more efficient by just returning the ID, but the moment I add the .Count() stage it starts to fail.
I cannot replicate this in compass, so I am bit confused as to what I am doing incorrectly. I also tried exporting my entire compass logic as a BsonDocument, and that works. It seems to be isolated to the way I am appending stages to the pipelines object, but I cannot figure out what I am doing incorrectly. I also found that I could not do a AppendStage.Count directly(hence the BsonStage Builder) because when I do that it complains that the entire pipeline needs to be a TOUT of AggregateCountResult. If I change my variable now none of the other pipelines stages will be inserted correctly.
Basically I have found multiple ways to get the result I want, but not using the C# syntax and examples are limited. I just seem to be stuck when attempting to use the C# syntax without converted my entire code to BsonDocuments and running them directly which I would like to avoid.