How to Use MongoDB in. Net,. netmongodb
What is MongoDB?
MongoDB is a document-based storage (rather than a table). It is a product between relational databases and non-relational databases. It features the most abundant and most like relational databases. The supported data structure is very loose and is similar to the json bson format, so it can store more complex data types. The biggest feature of Mongo is that it supports a very powerful query language. Its syntax is somewhat similar to an Object-Oriented Query Language. It can almost implement most of the functions similar to single-table queries in relational databases, it also supports data indexing. Mongo mainly solves the access efficiency problem of massive data. Because Mongo mainly supports massive data storage, it also comes with an excellent Distributed File System GridFS that supports massive data storage. Because Mongo supports complex data structures and has powerful data query functions, it is very popular.
BSON is the data storage format of MongoDB. Everyone is familiar with JSON, but what is BSON? BSON is based on the JSON format. The main reason for the transformation is the universality of json and the schemaless features of JSON.
BSON has the following features:
1. Faster traversal speed
For JSON format, a large JSON structure will lead to a very slow data traversal. In JSON, to skip a document for Data Reading, You need to scan the document and perform data structure matching, such as matching brackets. BSON's major improvement to JSON is, it will store the length of each element in JSON in the header of the element, so that you only need to read the element length and can directly read the seek to the specified point.
2. Easier operations
For JSON, data storage is non-typed. For example, you need to modify a basic value from 9 to 10, because it has changed from one character to two, therefore, it is possible that all the content after it must be moved back by one. With BSON, you can specify this column as a number column. Therefore, no matter the number ranges from 9 to 10 or 100, we only modify the column where the number is stored, does not increase the total data length. Of course, in MongoDB, if the number increases from an integer to a long integer, the total length of the data will increase.
3. added additional data types
JSON is a convenient data exchange format, but its type is limited. BSON adds the "byte array" data type. This eliminates the need for base64 conversion before storing binary data in JSON format. This greatly reduces computing overhead and data size. Of course, sometimes BSON has no space advantage over JSON because of the type concept.
Install MongoDB in windows
MongoDB installation is very simple. After the installation path is set up, Next continues until the installation is complete. The biggest pitfall is the MongoDB service installation. The following describes some configuration operations after MongoDB installation.
1. create the database path (data directory), Log Path (logs directory), and log file (mongo. log File), configuration path (conf directory), my installation path is: D: \ Program Files \ mongodb
2. Create the configuration file mongo. conf In the conf directory. The file content is as follows:
Logpath = D: \ Program Files \ mongodb \ logs \ mongodb. log # log output file path logappend = true # The Error log adopts the append mode. After this option is configured, mongodb logs will be appended to the existing log files, instead of creating a new file journal = true # enable log files, quiet = true by default # This option can filter out useless log information, if debugging is required, set it to falseport = 27017 # The default port number is 27017 auth = true # the user name and password are required for authentication.
After completing the preceding two steps, you can start MongoDB.
Run CMD and enter the command (note the mongod path)
mongod --config " D:\Program Files\mongodb\data \conf\mongo.conf"
3. Create and start the MongoDB Service
If you follow the steps in step 3 every time, it is not very troublesome. Follow the following command to create and start the MongoDB service, you can use the windows Service to manage MongoDB startup and shutdown.
mongod --config " D:\Program Files\mongodb\data \conf\mongo.conf" --install --serviceName "MongoDB"net start MongoDB
If the test is successful, enter http: // localhost: 27017 in the browser. If it appears, the service is successfully installed.
To uninstall the MongoDB service and run it in CMD
mongod.exe --remove --serviceName "MongoDB"
After the preparation is complete, you can start coding.
How to Use MongoDB in. net
First, introduce MongoDB in the project. bson. dll, MongoDB. driver. dll, MongoDB. driver. core. dll I am using version 2.0. Now many articles are about using version 1 +. This is also the purpose of writing this article. After introducing the driver DLL, you can start to compile the code.
Some code is as follows:
Private static MongoClient client; private static IMongoDatabase database; // configure private const string MongoDBConnectionStr = "mongodb: // localhost"; // The database name is private static string DefaultDataBaseName = "Test "; public jsondbhelper () {GetConnection (DefaultDataBaseName );} /// <summary> /// the constructor specifies the database // </summary> /// <param name = "dataBaseName"> </param> public MongoDBHelper (string dataBaseName) {GetConnection (DataBaseName);} private static void GetConnection (string dataBaseName) {client = new clients client (MongoDBConnectionStr); database = client. getDatabase (dataBaseName) ;}/// <summary> /// insert a data entry asynchronously, manually enter collection name // </summary> public Task InsertAsync <T> (string collectionName, T obj) {if (database = null) {throw new Exception ("no database specified");} var collection = database. getCollection <T> (collectionName); Return collection. insertOneAsync (obj);} // <summary> // insert a data entry asynchronously, use the fully qualified name of type T as collection name // </summary> public Task InsertAsync <T> (T obj) {return InsertAsync (typeof (T ). fullName, obj) ;}/// <summary> /// asynchronously inserts multiple data records, manually enter collection name // </summary> public Task BatchInsertAsync <T> (string collectionName, IEnumerable <T> objs) {if (database = null) {throw new Exception ("no database specified");} if (objs = nul L) {throw new ArgumentException ();} var collection = database. getCollection <T> (collectionName); return collection. insertManyAsync (objs);} // <summary> // asynchronously inserts multiple data records, use the fully qualified name of the type T as the collection name // </summary> public Task BatchInsertAsync <T> (IEnumerable <T> objs) {return BatchInsertAsync (typeof (T ). fullName, objs) ;}/// <summary> /// Insert a data record /// </summary> public void Insert <T> (T obj) {InsertAsync (obj ). wa It () ;}//< summary> /// Insert multiple data records /// </summary> public void Insert <T> (IEnumerable <T> objs) {BatchInsertAsync (objs ). wait () ;}//< summary> /// Find method of MongoDB C # Driver, and IFindFluent is returned. Manually enter collection name // </summary> public IFindFluent <T, T> Find <T> (string collectionName, FilterDefinition <T> filter, FindOptions options = null) {if (database = null) {throw new Exception ("no database specified");} var collection = database. getCollection <T> (collectionName); return collection. find (filter, options) ;}/// <summary> /// Find method of MongoDB C # Driver, and IFindFluent is returned. Use the fully qualified name of type T as collection name // </summary> public IFindFluent <T, T> Find <T> (FilterDefinition <T> filter, FindOptions options = null) {return Find (typeof (T ). fullName, filter, options) ;}/// <summary> /// multiple sorting conditions are separated by commas (,) in the data sort that meets the condition, default asc // </summary> public List <T> Get <T> (Expression <Func <T, bool> condition, int skip, int limit, string sort) {return Get (new List <Expression <Func <T, bool> {condition}, s Kip, limit, sort);} public List <T> Get <T> (Expression <Func <T, bool> condition) {return Get (condition, 0, 0, null);} // <summary> // separate multiple sorting conditions by commas (,) in the sort that meets the condition, default asc // </summary> public List <T> Get <T> (List <Expression <Func <T, bool> conditions, int skip, int limit, string sort) {if (conditions = null | conditions. count = 0) {conditions = new List <Expression <Func <T, bool >>{ x => true };} var B Uilder = Builders <T>. filter; var filter = builder. and (conditions. select (x => builder. where (x); var ret = new List <T> (); try {List <SortDefinition <T> sortDefList = new List <SortDefinition <T> (); if (sort! = Null) {var sortList = sort. split (','); for (var I = 0; I <sortList. length; I ++) {var sl = Regex. replace (sortList [I]. trim (), @ "\ s + ",""). split (''); if (sl. length = 1 | (sl. length> = 2 & sl [1]. toLower () = "asc") {sortDefList. add (Builders <T>. sort. ascending (sl [0]);} else if (sl. length> = 2 & sl [1]. toLower () = "desc") {sortDefList. add (Builders <T>. sort. descending (sl [0]) ;}} var sortDef = Builders <T>. sort. combine (sortDefList); ret = Find (filter ). sort (sortDef ). skip (skip ). limit (limit ). toListAsync (). result;} catch (Exception e) {// Exception Handling} return ret;} public List <T> Get <T> (List <Expression <Func <T, bool >>> conditions) {return Get (conditions, 0, 0, null );}
Only the insert and query functions are implemented in the sample code. The complete code will be uploaded later.
Summary
This article only records the most basic usage of MongoDB. We will introduce replica-level, master-slave automatic backup, and other mechanisms and implementation methods in the future. If you are interested, please stay tuned to the help house, thank you for your support.