Home > front end >  AggregateFluent and aggregate query
AggregateFluent and aggregate query

Time:10-15

I have the following aggregate query

aggregate(
[{"$facet": 
    {"home": [{"$match": {"$expr": {"$eq": ["$IsHomePage", true]}}}],
      "notHome": 
      [{"$match": 
          {"$expr": 
            {"$and": 
              [{"$ne": ["$IsHomePage", true]}, {"$eq": ["$IsTagged", true]}]}}},
        {"$sample": {"size": 50}}]}},
  {"$project": {"union": {"$concatArrays": ["$home", "$notHome"]}}},
  {"$unwind": {"path": "$union"}},
  {"$replaceRoot": {"newRoot": "$union"}}])

is it possible to store this code in the variable and than reference it from the AggregateFluent

return await db.posts.Aggregate<Post>(VARIABLE_NAME).ToListAsync();

CodePudding user response:

Not exactly, Aggregate supports PipelineDefinition as input argument which accepts each stage separately like:

  var pipeline = PipelineDefinition<Post, Post>.Create(
            "{ <aggregate stage1> }",
            "{ <aggregate stage2> }");

if you want to use the syntax that you mentioned above, you should use:

  var coll = db.GetCollection<Post>("coll")
            .Aggregate<Post>()
            .AppendStage<Post>("{ <stage1> }")
            .AppendStage<Post>("{ <stage2> }");

to create PipelineDefinition, you also can use EmptyPipelineDefinition:

  var pipelineDefinition = new EmptyPipelineDefinition<Post>()
            .AppendStage<Post, Post, Post>("{ <stage1> }")
            .AppendStage<Post, Post, Post>("{ <stage2> }");

also, pay attention that you can use a builder for facet itself for example:

   var pipeline = PipelineDefinition<BsonDocument, BsonDocument>.Create(
            "{ $unwind : \"$tags\" }",
            "{ $sortByCount : \"$tags\" }");
   var facet = AggregateFacet.Create("name", pipeline);

   var result = subject.Facet(facet);
  • Related