Back

MongoDB Aggregate Pipline

Here's an example of how to use MongoDB's Aggregate Pipeline to create more advanced queries which return a subset of document properties from a collection, similar to a GROUP BY clause.

MongoDB Aggregate Pipline

Here's an example of how to use MongoDB's Aggregate Pipeline to create more advanced queries which return a subset of document properties from a collection, similar to a GROUP BY clause.

Aggregate Pipline

Get the collection to be aggregated.

var coll = ReportsApp.DB.QuotationEquipments
  .mongoCollection;

Create a Query used to match specific documents.

var match = new BsonDocument{{
  "$match", new BsonDocument {
    {"cExist", "A"},
    {"nQuotationsId", 103632},          
  }
}};

Here's our Group By expression to reduce the result to unique SiteIds.

var group = new BsonDocument{{
  "$group", new BsonDocument {
    {"_id", "$nSiteId"},     
  }
}};

This projection converts the _id mongoDB result into a more relevantly named structure.

var project = new BsonDocument{{
  "$project", new BsonDocument {
    {"_id", 0},
    {"SiteId", "id"},
  }
}};

Limit the number of results to 3.

var limit = new BsonDocument{{
  "$limit", 3
}};

Create the pipline for the mongoDB Aggregate method.

var pipeline = new [] {
  match,
  group,
  project,
  limit,
};

Wrap the Pipeline into the specific AggregateArgs type.

var args = new AggregateArgs {
  Pipeline = pipeline,
  AllowDiskUse = true,
};

Execute the Aggregation for the collection.

var results = coll.Aggregate(args);

Deserialize the results into a C# object of type SiteIdResult.

var sites = results.Select(
  o => BsonSerializer.Deserialize<SiteIdResult>(o)
);

Loop over the results & generate a string for outputting.

var output = "";

// Loop over the results
foreach( var site in sites ){
  output += "Site : " + site.SiteId.ToString() + "\n";
}

The SiteIdResult Class

This class represents the result after the $project alters what structure MongoDB returns, and is the type that we deserialize to after the Aggerate execution.

public class SiteIdResult {
  public long SiteId { get; set; }
}

The resultant output

Here's the output generated via the aggregate pipeline above :

Start Test

Site : 103039
Site : 103043
Site : 103041

END