Skip to content

Instantly share code, notes, and snippets.

@sindbach
Created March 30, 2016 09:47
Show Gist options
  • Save sindbach/1bdc89766df80f7eb22d0ccd8f1be60a to your computer and use it in GitHub Desktop.
Save sindbach/1bdc89766df80f7eb22d0ccd8f1be60a to your computer and use it in GitHub Desktop.
A simple C# script to demo MongoDB aggregation performing group by count.
using System;
using MongoDB.Bson;
using MongoDB.Driver;
using System.Threading.Tasks;
using System.Linq;
/* Where document structure stored in localhost MongoDB : {token:"word"}
*/
namespace Aggregation_01
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Start Async ");
var client = new MongoClient("mongodb://localhost:27017");
var database = client.GetDatabase("test");
var collection = database.GetCollection<BsonDocument>("tokens");
Task t = queryDatabase(collection);
t.ContinueWith((str) =>
{
Console.WriteLine(str.Status.ToString());
Console.WriteLine("Query Ends.");
});
t.Wait();
Console.ReadKey();
}
public async static Task<string> queryDatabase(IMongoCollection<BsonDocument> collection)
{
Console.WriteLine("Query Starts...");
var aggregate = collection.Aggregate()
.Group(new BsonDocument { { "_id", "$token" }, { "count", new BsonDocument("$sum", 1) } })
.Sort(new BsonDocument { { "count", -1 } })
.Limit(10);
var results = await aggregate.ToListAsync();
foreach (var obj in results)
{
Console.WriteLine(obj.ToString());
}
return "finished";
}
}
}
@ugursinans
Copy link

ugursinans commented Apr 28, 2021

Hi @sindbach how to use this group pipeline with in Generic Types ? Is it possible ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment