MongoDB can perform aggregation operations, such as grouping by a specified key and evaluating a total or a count for each distinct group.
Use the Group stage to group by a specified key. In the Group stage, specify the group by key in the _id field. Group accesses fields by the field path, which is the field name prefixed by a dollar sign $
Follow the Install and Connect to MongoDB step to connect to a running MongoDB instance.
using System;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;
namespace MongoDB
{
class Program
{
static void Main(string[] args)
{
DataGrouping(args).Wait();
Console.WriteLine("Press Enter");
Console.ReadLine();
}
static async Task DataGrouping(string[] args)
{
var _connectionString = "mongodb://localhost:27017";
var _client = new MongoClient(_connectionString);
var _database = _client.GetDatabase("blog");
var _collection = _database.GetCollection("users");
var _aggregate = _collection.Aggregate().Group(new BsonDocument { { "_id", "$ZipCode" }, { "count", new BsonDocument("$sum", 1) } });
var _results = await _aggregate.ToListAsync();
}
}
}