Share in. NET examples of using MongoDB

Source: Internet
Author: User
Tags mongoclient mongodb windows
Recently in the study of MongoDB, online search found that the use of MongoDB in. NET article is either an early driver version, or very little information, so write an essay record, this article in detail to introduce to you. NET in the use of MongoDB method tutorial, the need for friends can reference, below to see together.

What is MongoDB

MongoDB is a document-based store (rather than a table), a product between a relational database and a non-relational database, the most versatile of the non-relational databases, most like relational databases. The data structure he supports is very loose and is a JSON-like Bson format, so you can store more complex data types. MONGO's biggest feature is that the query language he supports is very powerful, and its syntax is a bit like an object-oriented query language that almost implements most of the functionality of a relational database single-table query, and also supports indexing of data. MONGO mainly solves the problem of access efficiency of massive data. Because MONGO is primarily supporting massive data storage, MONGO also comes with an excellent distributed file system Gridfs that can support massive data storage. Because MONGO can support complex data structures and has powerful data query capabilities, it is very popular.

Bson is a data storage format for MongoDB. We are familiar with JSON, but what is Bson? Bson based on JSON format, the main reason to choose JSON for transformation is the universality of JSON and the schemaless characteristics of JSON.

Bson has the following characteristics

1. Faster traversal speed

In JSON format, too large a JSON structure can cause data traversal to be very slow. In JSON, to skip a document for data reading, this document needs to be scanned, and a cumbersome data structure match, such as the matching of parentheses, and bson a big improvement to JSON is that it will have the length of each element of the JSON element in the head, This allows you to read directly to the specified point by reading the element length.

2. Easy to operate

For JSON, data storage is untyped, for example, if you want to modify a basic value, from 9 to 10, since a character becomes two, everything behind it may need to be moved backwards. Using Bson, you can specify this column as a number, then whether the number from 9 to 10 or 100, we are only stored in the number of the one on the change, does not cause the total length of the data to become larger. Of course, in MongoDB, if the number is increased from shaping to a long integer, it will cause the total length of the data to grow larger.

3. Added additional data types

JSON is a convenient format for data interchange, but its type is relatively limited. The Bson adds a "byte array" data type based on it. This makes binary storage no longer required to be Base64 converted before being stored as JSON. Greatly reduces the computational overhead and data size. Of course, in some cases, Bson has no spatial advantage over JSON because of the type concept.

MongoDB Windows under Installation

MongoDB installation is very simple, set up the installation path, always next until the end of the installation, the largest pit is the installation of MongoDB service, the following specific after the MongoDB installation of some configuration operations

1. Create the database path (data directory), log path (logs directory), log file (Mongo.log file), Configuration path (conf directory) in the root directory my installation path is: D:\Program Files\mongodb

2. Create the configuration file mongo.conf in the Conf directory with the following file contents:

Logpath=d:\program files\mongodb\logs\mongodb.log #日志输出文件路径logappend =true #错误日志采用追加模式, When this option is configured, the MongoDB log is appended to the existing log file instead of the new file Journal=true #启用日志文件, Quiet=true #这个选项可以过滤掉一些无用的日志信息 is enabled by default, If you need to debug use set to falseport=27017 #端口号 default to 27017auth=true #启用验证 require username password

Configuration complete the above 2 steps to start MongoDB

Run the cmd Input command (note the path to the Mongod)

Mongod--config "D:\Program files\mongodb\data \conf\mongo.conf"

3. Create and start the MongoDB service

If every time you follow step three, it would be quite a hassle to create and start the MongoDB service by following the command below, you can manage the startup and shutdown of MongoDB through the Windows service


Mongod--config "D:\Program files\mongodb\data \conf\mongo.conf"--install--servicename "MongoDB" net start MongoDB

Test success can be entered in the browser http://localhost:27017/if the presence indicates that the service installation was successful

If you need to uninstall the MongoDB service to run in CMD


Mongod.exe--remove--servicename "MongoDB"

The pre-prep work is complete and you can start the code.

How to use MongoDB in. Net

First introduced in the project Mongodb.bson.dll,mongodb.driver.dll,mongodb.driver.core.dll I am using the 2.0 version of the present many articles are introduced using the 1+ version of the That's why I'm writing this article. Once the driver DLL is introduced, you can start the code.

Some of the code below

private static mongoclient client;private static imongodatabase database;//Local Configuration Private Const string  Mongodbconnectionstr = "Mongodb://localhost";//Database name private static string defaultdatabasename = "Test"; Public Mongodbhelper () {getconnection (defaultdatabasename);}///<summary>///constructor specifies the database///</summary>/// <param name= "DataBaseName" ></param>public mongodbhelper (String dataBaseName) {getconnection ( DataBaseName);} private static void Getconnection (string dataBaseName) {client = new mongoclient (mongodbconnectionstr); database = Client . Getdatabase (dataBaseName);} <summary>///asynchronously inserts a piece of data, manually entering the collection name///</summary>public Task insertasync<t> (string CollectionName, T obj) {if (database = = null) {throw new Exception ("No Databases Specified"),} var collection = database. Getcollection<t> (CollectionName); Return collection. Insertoneasync (obj);} <summary>///asynchronously inserts a piece of data with the fully qualified name of type T as collection name///</summary>public Task insertasync<t> (t obj) {return Insertasync (typeof (T). FullName, obj);} <summary>///inserts multiple data asynchronously, manually entering collection name///</summary>public Task batchinsertasync<t> (string   CollectionName, ienumerable<t> Objs) {if (database = = null) {throw new Exception ("No Databases Specified");} if (Objs = = null) { throw new ArgumentException (); } var collection = database. Getcollection<t> (CollectionName); Return collection. Insertmanyasync (OBJS);} <summary>///inserts multiple data asynchronously, using the fully qualified name of type T as collection name///</summary>public Task batchinsertasync<t > (ienumerable<t> objs) {return Batchinsertasync (typeof (T). FullName, OBJS);} <summary>///inserts a data///</summary>public void insert<t> (T obj) {insertasync (obj). Wait ();} <summary>///inserting more than one data//</summary>public void insert<t> (ienumerable<t> objs) { Batchinsertasync (OBJS). Wait ();} <summary>///MongoDB C # Driver's Find method, returns ifindfluent. Manual input Collection name///</summary>public IFINDFLUent<t, t> find<t> (String collectionname, filterdefinition<t> filter, findoptions options = null) {if ( Database = = null) {throw new Exception ("No Databases Specified");} var = collection = database. Getcollection<t> (CollectionName); Return collection. Find (filter, options);} <summary>///MongoDB C # Driver's Find method, returns ifindfluent. 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>///a comma-delimited list of multiple sorting criteria in the data sort that matches the criteria, the 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}, skip, limit, sort);} Public list<t> get<t> (expression<func<t, bool>> condition) {return Get (condition, 0, 0, null);} <summary>///to match the criteria of the data sort in multipleSorting criteria comma-delimited, 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 builder = Builde Rs<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 insert and query functionality is implemented in the sample code, and subsequent uploads of the full code

Summarize

This article only records the most basic use of MongoDB, the following will introduce the copy-level, master-slave automatic backup mechanism and implementation methods.

"Recommended"

1. ASP. NET free Video Tutorials

2. Python uses the MongoDB starter instance

3. Python Operation MongoDB Database Pymongo Library Usage method

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.