Tutorial on using mongodb in. Net

Time:2021-9-22

What is mongodb

Mongodb is based on document storage (not tables). It is a product between relational database and non relational database. It is the most functional and relational database among non relational databases. The data structure he supports is very loose, which is a JSON like bson format, so it can store more complex data types. Mongo’s biggest feature is that the query language he supports is very powerful. Its syntax is a bit similar to the object-oriented query language. It can almost realize most functions similar to single table query of relational database, and also supports indexing of data. Mongo mainly solves the problem of access efficiency of massive data. Because Mongo mainly supports massive data storage, Mongo also comes with an excellent distributed file system gridfs, which can support massive data storage. Mongo is very popular because it can support complex data structures and has powerful data query function.

Bson is the data storage format of mongodb. We are familiar with JSON, but what is bson? Bson is based on JSON format. The main reason for choosing JSON for transformation is the universality of JSON and the schemaless feature of JSON.

Bson has the following characteristics

1. Faster traversal speed

For JSON format, too large JSON structure will cause data traversal to be very slow. In JSON, if you want to skip a document for data reading, you need to scan the document, and you need to perform troublesome data structure matching, such as bracket matching. A great improvement of JSON by bson is that it will store the length of each element of JSON in the header of the element, In this way, you only need to read the element length, and you can directly seek to the specified point for reading.

2. Easier operation

For JSON, data storage is untyped. For example, you need to modify a basic value from 9 to 10. Since it has changed from one character to two, everything behind it may need to be moved back one bit. Using bson, you can specify this column as a number column. No matter whether the number is from 9 to 10 or 100, we only modify the bit where the number is stored, and the total length of the data will not become larger. Of course, in mongodb, if the number increases from integer to long integer, the total length of data will become larger.

3. Additional data types are added

JSON is a convenient data exchange format, but its types are limited. Bson adds the “byte array” data type to it. This makes binary storage no longer need to be Base64 converted and then stored as JSON. The computational overhead and data size are greatly reduced. Of course, sometimes bson has no spatial advantage over JSON because of the concept of type.

Mongodb installed under Windows

The installation of mongodb is very simple. After setting the installation path, continue to next until the installation is completed. The biggest pit is the installation of mongodb services. The following describes some configuration operations after mongodb installation

1. Create database path (data directory), log path (logs directory), log file (Mongo. Log file) and configuration path (CONF directory) under the root directory. My installation path is: D: \ program files \ mongodb

2. Create the configuration file mongo.conf in the conf directory. The contents of the file are 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, the mongodb log will be appended to the existing log file instead of creating a new file

Journal = true # enables log files, which are enabled by default

Quiet = true # this option can filter out some useless log information. If debugging is needed, please set it to false

Port = 27017 # port number is 27017 by default

Auth = true # enabling authentication requires a username and password

After completing the above two steps, you can start mongodb

Run CMD input command (note the path of mongod)


mongod --config " D:\Program Files\mongodb\data \conf\mongo.conf"

3. Create and start mongodb service

If you follow step 3 every time, isn’t it quite troublesome? Create and start the mongodb service according to the following command, and you can manage the startup and shutdown of mongodb through windows service


mongod --config " D:\Program Files\mongodb\data \conf\mongo.conf" --install --serviceName "MongoDB"

net start MongoDB 

Whether the test is successful can be entered in the browser http://localhost:27017/ If the following figure appears, the service installation is successful

If you need to uninstall mongodb service, run it in CMD


mongod.exe --remove --serviceName "MongoDB"

After the preliminary preparations are completed, you can start rolling out the code

How to use mongodb in. Net

First, introduce mongodb.bson.dll, mongodb.driver.dll and mongodb.driver.core.dll into the project. I use version 2.0. Now many articles introduce the use of version 1 +, which is also the purpose of my writing this article. After introducing the driver DLL, I can start rolling out the code

Some codes are as follows

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>

///Insert a piece of data asynchronously and enter collection name manually

/// </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 and use 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, and enter collection name manually

/// </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, and use 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 mongodb c# driver returns ifindfluent. 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>

///The find method of mongodb c# driver returns ifindfluent. Take 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>

///Multiple sorting conditions in the qualified data sort are separated by commas, and ASC is the default

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

///Multiple sorting conditions in the qualified data sort are separated by commas, and ASC is the default

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

}

The sample code only implements the functions of insertion and query, and the complete code will be uploaded later

summary

This article only records the most basic use of mongodb. Later, we will introduce replica level, master-slave automatic backup and other mechanisms and implementation methods. Interested friends, please continue to pay attention to developpaer. Thank you for your support for developpaer.