首页 > 代码库 > C# 操作mongodb 分组
C# 操作mongodb 分组
c#操作mongodb的分组的简单例子:
1、首先要下载c#对应的mongodb驱动,官方下载地址:https://github.com/mongodb/mongo-csharp-driver/releases,目前版本是2.3.0
然后引用相应的命名空间,
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Core;
2、实例代码:
/// <summary>
/// 数据集合,类似关系型数据库中的表
/// </summary>
static IMongoCollection<BsonDocument> _collect;
/// <summary>
/// 数据库初始化
/// </summary>
/// <param name="collectionName">数据集合名(就是数据库表名))</param>
public static void Init(string collectionName)
{
string mongoDB_Host = ConfigurationManager.AppSettings["MongoDB_Host"].ToString();
string mongoDB_DbName = ConfigurationManager.AppSettings["MongoDB_DbName"].ToString();
MongoDB.Driver.MongoClient mc = new MongoClient(mongoDB_Host);
IMongoDatabase _db = mc.GetDatabase(mongoDB_DbName);
_collect = _db.GetCollection<BsonDocument>(collectionName);
}
假设有这样一个数据集合:
{ "_id" : 1, "name" : "mike", "sex" : "男", "age" : 20 }
{ "_id" : 2, "name" : "Marry", "sex" : "女", "age" : 25 }
{ "_id" : 3, "name" : "Tom", "sex" : "女", "age" : 35 }
{ "_id" : 4, "name" : "Joe", "sex" : "女", "age" : 35 }
{ "_id" : 5, "name" : "Joe", "sex" : "女", "age" : 45 }
{ "_id" : 6, "name" : "John", "sex" : "男", "age" : 45 }
a、统计男女的数量
Sql: select $sex,count(1) from student group by $sex
BsonDocument db = new BsonDocument { { "_id", "$sex" }, { "count", new BsonDocument("$sum", 1) } };
var aggregate = _collect.Aggregate().Group(db);
List<BsonDocument> list = aggregate.ToList<BsonDocument>();
b、统计男女的总年龄
SQL: select sex,SUM(aget) totalAge from student group by sex
BsonDocument db = new BsonDocument { { "_id", "$sex" }, { "totalAge", new BsonDocument("$sum", "$age") } };
var aggregate = _collect.Aggregate().Group(db);
List<BsonDocument> list = aggregate.ToList<BsonDocument>();
C# 操作mongodb 分组