joetherod
joetherod

Reputation: 155

MongoDB .NET Fluent Aggregate Query

I'm trying to write the query below using the fluent syntax of MongoDB. I'm using the latest .NET driver. I don't like the strings for naming the columns and would prefer to not have to do the Bson Serialization as well.

var collection = _mongoDbClient.GetDocumentCollection<JobResult>();
var bsonDocuments = collection.Aggregate()
    .Group<BsonDocument>(new BsonDocument{ { "_id", "$RunDateTime" }, { "Count", new BsonDocument("$sum", 1) } })
    .Sort(new BsonDocument { { "count", -1 } })
    .Limit(20)
    .ToList();

foreach (var bsonDocument in bsonDocuments)
{
    jobResultRunDateTimes.Add(BsonSerializer.Deserialize<JobResultRunDateTime>(bsonDocument));
}

Upvotes: 2

Views: 3682

Answers (1)

peeyush singh
peeyush singh

Reputation: 1407

C# driver has implementation of LINQ targeting the mongo aggregation framework, so you should be able to do your query using standard linq operators.

The example below shows a group by (on an assumed property Id) and take the count of documents followed by sorting. In example below x would be of type JobResult, i.e. type you use when getting the collection.

var result = collection.AsQueryable().GroupBy(x => x.Id).
Select(g=>new { g.Key, count=g.Count()}).OrderBy(a=>a.Key).Take(1).ToList();

For detailed reference and more example refer to C# driver documentation

Upvotes: 3

Related Questions