-
-
Save sindbach/1bdc89766df80f7eb22d0ccd8f1be60a to your computer and use it in GitHub Desktop.
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"; | |
} | |
} | |
} |
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.
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.
Hi @sindbach how to use this group pipeline with in Generic Types ? Is it possible ?
Hi is it possible to use Expressions in
Group()
instead of defining aBsonDocument
?