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";
}
}
}
@sebainones
Copy link

I have quite the same or similar question as @tanvi-khade.
I'm looking for some examples of Group() but instead of using BsonDocument I would like to see how it could be done with Lambdas for example:(not real example)
var aggregate = collection.Aggregate() .Group(c =>c.Date) ...
Again, this is not at all a real example. In fact, is what I want to find: a good example that I can follow.

@sindbach
Copy link
Author

sindbach commented Oct 9, 2020

Hi @tanvi-khade and @sebainones,

Assuming that you have the class mapping, then you should be able to. Extending the example above, say you have these two class mappings:

        public class MyClass 
        {
            [BsonId]
            private ObjectId Id {get; set;}
            [BsonElement("token")]
            public string Token { get; set; }
        }

        internal class Output
        {
            public ObjectId Id { get; set; }    
            public string Token {get; set;}
            public double Count { get; set; }
        }

Then, in your aggregation pipeline you could use the following to return a similar result:

            var docs = collection.Aggregate()
                                    .Group(y=>y.Token,
                                           z => new { 
                                               Token = z.Key, 
                                               Count = z.Sum(a => 1)
                                            }
                                    ).ToList();

If you have further questions, please post a question on https://developer.mongodb.com/community/forums/ with the following information:

  • MongoDB .NET/C# driver version
  • Example code snippets
  • Example document input (in the database)
  • Expected output

Regards,
Wan.

@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