/// <summary> /// Appends a sortByCount stage to the pipeline. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <typeparam name="TKey">The type of the key.</typeparam> /// <param name="aggregate">The aggregate.</param> /// <param name="id">The id.</param> /// <returns> /// The fluent aggregate interface. /// </returns> public static IAggregateFluent <AggregateSortByCountResult <TKey> > SortByCount <TResult, TKey>( this IAggregateFluent <TResult> aggregate, Expression <Func <TResult, TKey> > id) { Ensure.IsNotNull(aggregate, nameof(aggregate)); return(aggregate.AppendStage(PipelineStageDefinitionBuilder.SortByCount(id))); }
private IEnumerable <AggregateFacet <Recipe, AggregateSortByCountResult <string> > > CreateFacet() { foreach (var facet in _facets) { yield return(AggregateFacet.Create(facet.Replace(".", "_"), PipelineDefinition <Recipe, AggregateSortByCountResult <string> > .Create(new[] { PipelineStageDefinitionBuilder.SortByCount <Recipe, string>($"${facet}") }))); } }
public void Facets() { var collection = new MongoClient("mongodb://localhost:27017/admin").GetDatabase("firstdb").GetCollection <Book>("book"); var car1 = new Book() { Name = "b1", Tags = new System.Collections.Generic.Dictionary <string, string>() { { "Edition", "Blah" }, { "Published", "2018" } } }; collection.InsertOne(car1); var pipelinex = collection.Aggregate() .Match(b => b.Name == "b1") .Project("{Tags: { $objectToArray: \"$Tags\" }}") .Unwind("Tags") .SortByCount <BsonDocument>("$Tags"); var outputx = pipelinex.ToList(); var json = outputx.ToJson(new JsonWriterSettings { Indent = true }); var project = PipelineStageDefinitionBuilder.Project <Book, BsonDocument>("{Tags: { $objectToArray: \"$Tags\" }}"); var unwind = PipelineStageDefinitionBuilder.Unwind <BsonDocument, BsonDocument>("Tags"); var sortByCount = PipelineStageDefinitionBuilder.SortByCount <BsonDocument, BsonDocument>("$Tags"); var pipeline = PipelineDefinition <Book, AggregateSortByCountResult <BsonDocument> > .Create(new IPipelineStageDefinition[] { project, unwind, sortByCount }); // string based alternative version //var pipeline = PipelineDefinition<Book, BsonDocument>.Create( // "{ $project :{ Tags: { $objectToArray: \"$Tags\" } } }", // "{ $unwind : \"$Tags\" }", // "{ $sortByCount : \"$Tags\" }"); var facetPipeline = AggregateFacet.Create("categorizedByTags", pipeline); var aggregation = collection.Aggregate().Match(b => b.Name == "b1").Facet(facetPipeline); var listx = aggregation.ToList(); // var outputxy = listx.Facets.ToJson(new JsonWriterSettings { Indent = true }); var output = aggregation.Single().Facets.ToJson(new JsonWriterSettings { Indent = true }); Console.WriteLine(output); }