First to https://github.com/mongodb/mongo-csharp-driver/downloads download MONGO official driver
Refer to the project when the download is complete
Public classConnhelp { Public Static stringConnectionString ="Mongodb://127.0.0.1:27017/qiao"; Public Staticmongodatabase getdatabasefromurl (mongourl url) {varClient =Newmongoclient (URL); varServer =client. Getserver (); returnserver. Getdatabase (URL. DatabaseName); } Public StaticMongodatabase getdatabasefromconnectionstring (stringConnectionString) { returnGetdatabasefromurl (NewMongourl (connectionstring)); } Public StaticMongocollection<t> getcollection<t> (stringCollectionName) { returnGetdatabasefromconnectionstring (ConnectionString). Getcollection<t>(CollectionName); } }
usingMongodb.bson;usingMongodb.driver;usingMongoDB.Driver.Builders;usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacemognolearn{classProgram {Static voidMain (string[] args) {mongocollection<aa> TT = connhelp.getcollection<aa> ("AA"); //list<aa> = TT. FindAll (). ToList (); varquery = Query.and (QUERY<AA>. EQ (x = X.name,"Zhang San")); //{"name": "Zhang San"}list<aa> LL = tt. Find (query). ToList ();//to return data based on the criteria of querylist<aa> list = TT. FindAll (). ToList ();//querying all of the datalist<string> str =Newlist<string>(); Str. ADD ("Zhang San"); Str. ADD ("John Doe"); Query=Query.and (Query<aa>. In (x=>x.name,str)); //{"name": {"$in": ["Zhang San", "John Doe"]}}List =TT. Find (query). ToList (); //aggregating an inline document books in a database//If you need to filter out some data, write the filter in this place .//var match = new Bsondocument//{ // { //"$match",//query. Tobsondocument ()// } //}; varUnwind =Newbsondocument {{"$unwind", "$books" } }; //unwind can also write some filters to filter out some data that may not be needed after splitting. varGroup =Newbsondocument {{"$group", Newbsondocument {{"_id",Newbsondocument {{"Books","$books. Name" }, { " Money","$money" } } }, { "Count",Newbsondocument {{"$sum",1} } } } } }; Aggregateresult Use=TT. Aggregate (unwind, group); varSttr = use. Response.tolist () [0]. Value; //{[{"_id": {"Books": "Creature"}, "Count": 1}, {"_id": {"Books": "Geography"}, "Count": 1}, {"_id": {"Books": "Chemistry" }, "Count": 4},
{"_id": {"Books": "English"}, "Count": 2}, {"_id": {"Books": "Language"}, "Count": 7}, {"_id": {"books": "Math"}, "C Ount ": 2}, {" _id ": {" books ":" Mongo authoritative Guide "}," Count ": 1}]}Console.ReadLine (); } }}
namespacemognolearn{ Public classAA {//[Bsonid][Bsonrepresentation (Bsontype.objectid)] Public stringID {Get;Set; } Public stringName {Get;Set; } PublicList<book> Books {Get;Set; } //[Bsondatetimeoptions (Kind = datetimekind.local)]//Public DateTime Addtime {get; set;} } Public classBook { Public stringName {Get;Set; } Public DoubleMoney {Get;Set; } Public intPage {Get;Set; } }}
Using MONGO official drive operation MONGO Database