A simple example of C # operation MongoDB Grouping:
1, first to download C # corresponding to the MongoDB driver, the official: https://github.com/mongodb/mongo-csharp-driver/releases, the current version is 2.3.0
Then reference the appropriate namespace,
Using Mongodb.bson;
Using Mongodb.driver;
Using MongoDB.Driver.Core;
2. Example code:
<summary>
data sets, tables in similar relational databases
</summary>
Static imongocollection<bsondocument> _collect;
<summary>
Database initialization
</summary>
<param name= "CollectionName" > Data set name (that is, database table name) </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);
}
Suppose you have such a data collection:
{"_id": 1, "name": "Mike", "Sex": "Male", "Age": 20}
{"_id": 2, "name": "Marry", "Sex": "Female", "Age": 25}
{"_id": 3, "name": "Tom", "Sex": "Female", "Age": 35}
{"_id": 4, "name": "Joe", "Sex": "Female", "Age": 35}
{"_id": 5, "name": "Joe", "Sex": "Female", "Age": 45}
{"_id": 6, "name": "John", "Sex": "Male", "Age": 45}
A. Statistics on the number of men and women
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. Statistics on the total age of men and women
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 # manipulating MongoDB groupings