. A tutorial on how to use MongoDB in net

Source: Internet
Author: User
Tags mongoclient mongodb windows name database
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 #log output file path

logappend = true #The error log adopts append mode. After configuring this option, mongodb's log will be appended to the existing log file, instead of creating a new file from scratch

journal = true #Enable journal files, enabled by default

quiet = true #This option can filter out some useless log information. If debugging is required, please set it to false

port = 27017 #port number default is 27017

auth = true #Enable authentication requires username and 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";

//Name database

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>

/// Insert a piece of data asynchronously, manually enter the 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 piece of data asynchronously, using the fully qualified name of type T as the collection name

/// </ summary>

public Task InsertAsync <T> (T obj)

{

 return InsertAsync (typeof (T) .FullName, obj);

}

 

/// <summary>

/// Insert multiple pieces of data asynchronously, manually enter the collection name

/// </ summary>

public Task BatchInsertAsync <T> (string collectionName, IEnumerable <T> objs)

{

 if (database == null)

 {

  throw new Exception ("No database specified");

 }

 if (objs == null)

 {

  throw new ArgumentException ();

 }

 var collection = database.GetCollection <T> (collectionName);

 return collection.InsertManyAsync (objs);

}

 

/// <summary>

/// Insert multiple pieces of data asynchronously, using the fully qualified name of type T as the collection name

/// </ summary>

public Task BatchInsertAsync <T> (IEnumerable <T> objs)

{

 return BatchInsertAsync (typeof (T) .FullName, objs);

}

 

/// <summary>

/// insert a piece of data

/// </ summary>

public void Insert <T> (T obj)

{

 InsertAsync (obj) .Wait ();

}

 

/// <summary>

/// insert multiple pieces of data

/// </ summary>

public void Insert <T> (IEnumerable <T> objs)

{

 BatchInsertAsync (objs) .Wait ();

}

 

/// <summary>

/// The Find method of the MongoDB C # Driver returns IFindFluent. Enter collection name manually

/// </ 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>

/// The Find method of the MongoDB C # Driver returns IFindFluent. Use the fully qualified name of type T as the collection name

/// </ summary>

public IFindFluent <T, T> Find <T> (FilterDefinition <T> filter, FindOptions options = null)

{

 return Find (typeof (T) .FullName, filter, options);

}

 

/// <summary>

/// Take the eligible data. Multiple sort conditions in the sort are comma separated. The default is 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>

/// Take the eligible data. Multiple sort conditions in the sort are comma separated. The default is 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 = 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 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, follow-up will introduce the replica level, master-slave automatic backup and other mechanisms and implementation, interested friends please continue to focus on the script home, thank you for the script home support.


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.