Created
March 30, 2016 09:47
-
-
Save sindbach/1bdc89766df80f7eb22d0ccd8f1be60a to your computer and use it in GitHub Desktop.
A simple C# script to demo MongoDB aggregation performing group by count.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @sindbach how to use this group pipeline with in Generic Types ? Is it possible ?