First, the installation of MongoDB
MongoDB is installed under Windows with the Auth mode enabled service
Second, download the driver
Use NuGet to search for "MongoDB", Download "Mongodb.driver" (this is an official recommended driver, completely free), it will automatically download "Mongodb.bson", "MongoDB.Driver.Core"
API Document Address
Third, code writing
1, new four classes: commodity, commodity sales status enumeration, product review, product review review status enumeration
Using System.componentmodel;namespace models{///<summary>//Copyright (C) YJQ All rights reserved. Class Name: ProductSaleState.cs///Class Property: public Class (non-static)///class function Description: Product sales status//Create identity: YJQ 2017/5/21 0:36:02//</SUMMARY&G T public enum Productsalestate {//<summary>///For review//</summary> [Descriptio N ("Pending Review")] Waitingcheck = 1,///<summary>///</summary> [Descriptio N ("shelves")] OnSale = 2,//<summary>///lower shelf///</summary> [Description ("lower shelf") ] Offshelves = 3,///<summary>//Sales///</summary> [Description ("sold")] saled = 4}}using system.componentmodel;namespace models{//<summary>//Copyright (C) YJQ All rights reserved. Class Name: CommentCheckState.cs///Class Property: public Class (non-static)///Class Function Description: Review audit status//Create identity: YJQ 2017/5/21 0:51:43//</summary& Gt public enum Commentcheckstate {//<summary>///For review///</summary> [Description ("Pending review")] Waitingcheck = 1,///<summary>///review via//</summary> [Description ("Audit Pass")] Passed = 2,///<summary>///Review not passed//</summary> [Description ("Audit not approved")] Notpass = 3}}using infrastructure;using mongodb.bson;using mongodb.bson.serialization.attributes;using System;usin G System.collections.generic;namespace models{///<summary>//Copyright (C) 2015 spare tires All rights reserved. Class Name: Product.cs///Class Property: public Class (non-static)///class Function Description: Goods///Create Logo: YJQ 2017/5/18 14:59:35///</summary> Sealed class Product {public product () {} public product (string name, decimal price): t His () {Id = Objectid.generatenewid (); name = name; Price = Price; Salestate = Productsalestate.waitingcheck; Createtime = DateTime.Now; }///<summary>//Product ID//</summary> [Bsonelement (elementname: "_id")] P Ublic ObjectId Id {get; set;} <summary>///Product Name///</summary> public string name {get; set;} <summary>///Price///</summary> public decimal? Price {get; set;} <summary>///Sales status///</summary> public productsalestate salestate {get; set;} <summary>//Add time///</summary> [bsondatetimeoptions (Kind = datetimekind.local )] public DateTime createtime {get; set;} <summary>//modification time///</summary> [bsondatetimeoptions (Kind = datetimekind.local)] Public DateTime? modifytime {get; set;} <summary>///Product Reviews///</summary> public list<productComment> Comments {get; set;} public override string ToString () {return $ ' {Id}:{name}, price {value}, Audit status {SALESTATE.DESC ()} "; }}}using infrastructure;using mongodb.bson;using mongodb.bson.serialization.attributes;using System;namespace models{//<summary>//Copyright (C) 2015 spare births. Class Name: ProductComment.cs///Class Property: public Class (non-static)///class Function Description: Product review//Create Logo: YJQ 2017/5/18 15:08:32//</summary> public sealed class Productcomment {//<summary>///Comment ID//</summary> [ Bsonelement (elementname: "_id")] public ObjectId ID {get; set;} <summary>///comments///</summary> public string content {get; set;} <summary>///Review status///</summary> public commentcheckstate checkstate {get; set;} <summary>//Add time///</summary> [BsondatetimeoptioNS (Kind = datetimekind.local)] public DateTime createtime {get; set;} <summary>//modification time///</summary> [bsondatetimeoptions (Kind = datetimekind.local)] Public DateTime? modifytime {get; set;} public override string ToString () {return $ "comment information: {Content}, Audit status: {Checkstate.desc ()}"; } }}
2, we first make a new Apple, the price is 5.2, and the audit status for review, and then in the query product list, output all the goods, and show its status
Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading.Tasks; Using mongodb.driver;using models;using Mongodb.bson;namespace mongodbtest{class Program {private static St Ring _MONGODBCONNECTIONSTR = "Mongodb://yjq:[email protected]:27017/admin"; static void Main (string[] args) {var productcollection = getcollection<product> (); Add an item to be audited product Product = new Product ("Apple", (decimal) 5.20); Productcollection.insertone (product); Console.WriteLine ($ "Add Product: {product. ToString ()} succeeded. "); var productlist = productcollection.find (New Bsondocument ()). ToList (); foreach (var item in productlist) {Console.WriteLine (item. ToString ()); } console.read (); } private static Imongocollection<t> getcollection<t> (string collectionname = null) { Mongourl moNgourl = new Mongourl (_MONGODBCONNECTIONSTR); var mongoclient = new Mongoclient (Mongourl); var database = Mongoclient.getdatabase (mongourl.databasename); return database. Getcollection<t> (CollectionName?? typeof (T). Name); } }}
Open with Robomongodb and look at the corresponding information, we will find that the database is stored 8 hours later than our current time, because the default time zone is not our local time zone when we install MongoDB, but as long as it is marked on the Time field [ Bsondatetimeoptions (Kind = datetimekind.local)] will be able to display our local time in the output.
Here, we have completed a simple new and query function, then we first randomly insert a few audit pass, do not pass, pending approval of a total of 100 products.
The code is as follows:
Change the Product code
Using infrastructure;using mongodb.bson;using mongodb.bson.serialization.attributes;using System;using System.collections.generic;namespace models{//<summary>//Copyright (C) 2015 spare births. Class Name: Product.cs///Class Property: public Class (non-static)///class Function Description: Goods///Create Logo: YJQ 2017/5/18 14:59:35///</summary> Sealed class Product {public product () {} public product (string name, decimal price): t His (name, Price, Productsalestate.waitingcheck) {} public Product (string name, decimal price, produc Tsalestate salestate) {Id = Objectid.generatenewid (); name = name; Price = Price; Salestate = salestate; Createtime = DateTime.Now; }///<summary>//Product ID//</summary> [Bsonelement (elementname: "_id")] P Ublic ObjectId Id {get; set;} <summary>//Product Name///</SUMMARY> public string Name {get; set;} <summary>///Price///</summary> public decimal? Price {get; set;} <summary>///Sales status///</summary> public productsalestate salestate {get; set;} <summary>//Add time///</summary> [bsondatetimeoptions (Kind = datetimekind.local )] public DateTime createtime {get; set;} <summary>//modification time///</summary> [bsondatetimeoptions (Kind = datetimekind.local)] Public DateTime? modifytime {get; set;} <summary>///Product Reviews///</summary> public list<productcomment> Comments {get; s Et } public override string ToString () {return $ ' {Id}:{name}, price {value}, Audit status {SALESTATE.DESC ()} "; } }}
Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading.Tasks; Using mongodb.driver;using models;using Mongodb.bson;namespace mongodbtest{class Program {private static St Ring _MONGODBCONNECTIONSTR = "Mongodb://yjq:[email protected]:27017/admin"; static void Main (string[] args) {var productcollection = getcollection<product> (); Add an item to be audited//product Product = new Product ("Apple", (decimal) 5.20); Productcollection.insertone (product); Console.WriteLine ($ "Add Product: {product. ToString ()} succeeded. "); Bulk increase commodity list<product> productaddlist = new list<product> (); for (int i = 0; i < i++) {Productaddlist.add (getrandomproduct ()); } productcollection.insertmany (Productaddlist); var productlist = productcollection.find (New Bsondocument ()). ToList (); foreach (var item in productlist) {Console.WriteLine (item. ToString ()); } console.read (); } private static Imongocollection<t> getcollection<t> (string collectionname = null) { Mongourl Mongourl = new Mongourl (_MONGODBCONNECTIONSTR); var mongoclient = new Mongoclient (Mongourl); var database = Mongoclient.getdatabase (mongourl.databasename); return database. Getcollection<t> (CollectionName?? typeof (T). Name); } private static string[] _productnames = new string[] {"Apple", "banana", "pineapple", "cantaloupe", "watermelon", "cucumber", "strawberry", "peach", "mango", "macaque Peach "," pear "}; private static Random rn = new random (); private static Product getrandomproduct () {var i = rn. Next (_productnames.length); Decimal Price = i * 15; var enumvalue = rn. Next (1, 5); return new Product (_productnames[i], price, (productsalestate) enumvalue); } }}
Then run, you can go to robo to see the results, found in the database there are a total of 101 data
The bulk increment operation is also executed, then we continue to perform paging and modify the deletion function.
First, we first query the total number of records returned and the first 20 items of information content:
Program
Because the product is randomly generated, it may result in different results between you and me.
Next we check the items to be audited, and show the total number of items to be audited, we change the next filte (using lambda expression tree is convenient), the second choice can be
Expression<func<product, bool>> expression = m = = M.salestate = = Productsalestate.waitingcheck; Long Productallcount = productcollection.count (expression); var productlist = productcollection.find (expression). Skip (0). Limit (20). ToList (); Console.foregroundcolor = consolecolor.red; Console.WriteLine ($ "Total record number is {productallcount.tostring ()}"); Console.foregroundcolor = Consolecolor.blue; Console.WriteLine ("The first 20 commodity information is:"); Console.foregroundcolor = Consolecolor.white; foreach (var item in productlist) { Console.WriteLine (item. ToString ()); }
#region Pending Review Filter Build var filter = Builders<product>. Filter.eq ("Salestate", Productsalestate.waitingcheck); Long Productallcount = Productcollection.count (filter); var productlist = Productcollection.find (filter). Skip (0). Limit (20). ToList (); Console.foregroundcolor = consolecolor.red; Console.WriteLine ($ "Total record number is {productallcount.tostring ()}"); Console.foregroundcolor = Consolecolor.blue; Console.WriteLine ("The first 20 commodity information is:"); Console.foregroundcolor = Consolecolor.white; foreach (var item in productlist) { Console.WriteLine (item. ToString ()); } #endregion
Next we review the 1th item to be audited by the operation, and add a "wow, this good eat Ah!" "The comment.
Using infrastructure;using mongodb.bson;using mongodb.bson.serialization.attributes;using System;using System.collections.generic;namespace models{//<summary>//Copyright (C) 2015 spare births. Class Name: Product.cs///Class Property: public Class (non-static)///class Function Description: Goods///Create Logo: YJQ 2017/5/18 14:59:35///</summary> Sealed class Product {public product () {} public product (string name, decimal price): t His (name, Price, Productsalestate.waitingcheck) {} public Product (string name, decimal price, produc Tsalestate salestate) {Id = Objectid.generatenewid (); name = name; Price = Price; Salestate = salestate; Createtime = DateTime.Now; }///<summary>//Product ID//</summary> [Bsonelement (elementname: "_id")] P Ublic ObjectId Id {get; set;} <summary>//Product Name///</SUMMARY> public string Name {get; set;} <summary>///Price///</summary> public decimal? Price {get; set;} <summary>///Sales status///</summary> public productsalestate salestate {get; set;} <summary>//Add time///</summary> [bsondatetimeoptions (Kind = datetimekind.local )] public DateTime createtime {get; set;} <summary>//modification time///</summary> [bsondatetimeoptions (Kind = datetimekind.local)] Public DateTime? modifytime {get; set;} <summary>///Product Reviews///</summary> public list<productcomment> Comments {get; s Et } public override string ToString () {return $ ' {Id}:{name}, price {value}, Audit status {SALESTATE.DESC ()} "; public void Showcomments () {if (Comments! = null) {forEach (var item in Comments) {Console.WriteLine (item. ToString ()); }}} public void Comment (string content) {if (Comments = = null) {Comments = new list<models.productcomment> (); } comments.add (new Models.productcomment (content)); } }}
Using infrastructure;using mongodb.bson;using mongodb.bson.serialization.attributes;using System;namespace Models{/ <summary>//Copyright (C) 2015 spare births. Class Name: ProductComment.cs///Class Property: public Class (non-static)///class Function Description: Product review//Create Logo: YJQ 2017/5/18 15:08:32//</summary> public sealed class Productcomment {public productcomment (string content) {if (content = = NULL) {throw new ArgumentNullException ("content"); } Id = Objectid.generatenewid (); Content = content; CheckState = Commentcheckstate.waitingcheck; Createtime = DateTime.Now; }///<summary>//Comment ID//</summary> [Bsonelement (elementname: "_id")] P Ublic ObjectId Id {get; set;} <summary>///comments///</summary> public string content {get; set;} <summary>//Review review status </summary> public commentcheckstate CheckState {get; set;} <summary>///Add time///</summary> [bsondatetimeoptions (Kind = datetimekind.local)] Public DateTime createtime {get; set;} <summary>//modification time///</summary> [bsondatetimeoptions (Kind = datetimekind.local)] Public DateTime? modifytime {get; set;} public override string ToString () {return $ "comment information: {Content}, Audit status: {Checkstate.desc ()}"; } }}
var beforeupdateproduct = productcollection.find (m = = M.salestate = = Productsalestate.waitingcheck). FirstOrDefault (); Console.WriteLine ($ "update before information {beforeupdateproduct?. ToString ()} "); Note Thread safety, here just to do demo beforeupdateproduct.comment ("Wow, this is good to eat!") "); var updatefilter = Builders<product>. Update.set (M = m.salestate, Productsalestate.onsale). Set (M = m.modifytime, DateTime.Now). Set (M = m.comments, beforeupdateproduct.comments); var updateresult = productcollection.updateone (m = m.id = = beforeupdateproduct.id, updatefilter); if (updateresult.ismodifiedcountavailable) {var afterupdateproduct = productcollection.find (M = > m.id = = beforeupdateproduct.id). FirstOrDefault (); Console.WriteLine ("Update Sales status Success ====="); Console.WriteLine ($ "post-update information {afterupdateproduct?. ToString ()} "); Console.WriteLine ("Comment Information:"); Afterupdateproduct.showcomments (); } else {Console.WriteLine ("Update failed ====="); }
Next we look for a list of items that have comments pending approval
var commentwaitingcheckproducts = productcollection.find (M = m.comments.where (k = K.checkstate = = Commentcheckstate.waitingcheck). Any ()). Toenumerable (); foreach (var item in commentwaitingcheckproducts) { Console.WriteLine (item. ToString ()); }
var projection = Builders<product>. Projection.expression (m = new Productdto { Comments = m.comments, Id = m.id, Name = M.name, Price = M.price, salestate = M.salestate }); var commentwaitingcheckproducts = productcollection.find (M = m.comments.where (k = K.checkstate = = Commentcheckstate.waitingcheck). Any ()). Project (projection). Toenumerable (); foreach (var item in commentwaitingcheckproducts) { Console.WriteLine (item. ToString ()); }
The simple operation is here, and some of the other operations can be based on documentation, and driving support for Lambda can make it easier for us to get started by querying some difficult queries.
API document address, the sample source download
C # Simple Operation mongodb_2.4