C# 操作mongodb 分組

來源:互聯網
上載者:User

標籤:

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 分組

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.