Home Backend Development C#.Net Tutorial Tutorial on how to use MongoDB in .Net

Tutorial on how to use MongoDB in .Net

May 28, 2017 am 10:18 AM

Recently researching mongodb, I searched on the Internet and found that articles about using mongodb in .net are either early driver versions, or there is very little information. So I wrote an essay to record it. This article introduces to you in detail the tutorial on how to use MongoDB in .Net. Friends in need can refer to it. Let’s take a look together.

What is MongoDB

MongoDB is based on document storage (not tables), and is between a relational database and a non-relational database The products among them are the most feature-rich among non-relational databases and most similar to relational databases. The data structure it supports is very loose and is a bson format similar to

json, so it can store more complex data types. The biggest feature of Mongo is that the query language it supports is very powerful. Its syntax is somewhat similar to the object-oriented query language. It can almost realize most functions similar to single-table queries in relational databases. , and also supports the establishment of index on 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 functions.

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 choosing JSON for transformation is the versatility of JSON and the schemaless characteristics of JSON.

BSON has the following characteristics

1. Faster traversal speed

For JSON format Generally speaking, a JSON structure that is too large 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 major improvement of BSON to JSON is that it will The length of each element is stored in the header of the element, so that you only need to read the length of the element to directly seek to the specified point for reading.

2. Easier operation

For JSON, data storage is untyped. For example, if you want to modify a basic value from 9 to 10, because from One character becomes two, so all the content after it may need to be moved back one position. Using BSON, you can specify this column as a numeric column. Then, no matter the number grows from 9 to 10 or 100, we will only modify the bit where the number is stored, which will not cause the total length of the data to become larger. Of course, in MongoDB, if the number increases from integer to long integer, the total data length will still increase.

3. Added additional data types

JSON is a very convenient data exchange format, but its types are relatively limited. BSON adds the "byte

array" data type on its basis. This eliminates the need to convert binary data to base64 before saving it to JSON. Computational overhead and data size are greatly reduced. Of course, sometimes, BSON does not have a space advantage over JSON because of the type concept.

MongoDB under windowsInstallation

The installation of MongoDB is very simple. After setting the installation path, it has been

Next Until the end of the installation, the biggest pitfall is the installation of the MongoDB service. Here are some configuration operations after the MongoDB installation

1. Create the database

path in the root directory ( data directory), log path (logs directory), 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 #日志输出文件路径

logappend=true #错误日志采用追加模式,配置这个选项后mongodb的日志会追加到现有的日志文件,而不是从新创建一个新文件

journal=true #启用日志文件,默认启用

quiet=true #这个选项可以过滤掉一些无用的日志信息,若需要调试使用请设置为false

port=27017 #端口号 默认为27017

auth=true #启用验证 需要用户名密码
Copy after login

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"
Copy after login

3. Create and start the MongoDB service

Wouldn’t it be quite troublesome if you follow step three every time? Follow the following command to create and start the MongoDB service. After starting the MongoDB service, 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
Copy after login

测试是否成功 可以在 浏览器中输入http://localhost:27017/如果出现下图表示服务安装成功

如果需要卸载MongoDB服务 在CMD 中运行

mongod.exe --remove --serviceName "MongoDB"
Copy after login

前期准备工作完成了,就可以开始撸代码了

如何在.net 中使用MongoDB

首先在项目中引入 MongoDB.Bson.dll,MongoDB.Driver.dll,MongoDB.Driver.Core.dll 我使用的是2.0版本的 现在好多文章都是介绍使用1+版本的 这也是我写此文的目的引入驱动DLL后,就可以开始撸代码了

部分代码如下

private static MongoClient client;

private static IMongoDatabase database;

//本地配置

private const string MongoDBConnectionStr = "mongodb://localhost";

//数据库名称

private static string DefaultDataBaseName = "Test";

 

 

public MongoDBHelper()

{

 GetConnection(DefaultDataBaseName);

}

 

/// <summary>

/// 构造函数 指定数据库

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

/// 异步插入一条数据,手动输入collection name

/// </summary>

public Task InsertAsync<T>(string collectionName, T obj)

{

 if (database == null)

 {

  throw new Exception("没有指定数据库");

 }

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

 return collection.InsertOneAsync(obj);

}

 

/// <summary>

/// 异步插入一条数据,采用类型T的完全限定名作为collection name

/// </summary>

public Task InsertAsync<T>(T obj)

{

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

}

 

/// <summary>

/// 异步插入多条数据,手动输入collection name

/// </summary>

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

{

 if (database == null)

 {

  throw new Exception("没有指定数据库");

 }

 if (objs == null)

 {

  throw new ArgumentException();

 }

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

 return collection.InsertManyAsync(objs);

}

 

/// <summary>

/// 异步插入多条数据,采用类型T的完全限定名作为collection name

/// </summary>

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

{

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

}

 

/// <summary>

/// 插入一条数据

/// </summary>

public void Insert<T>(T obj)

{

 InsertAsync(obj).Wait();

}

 

/// <summary>

/// 插入多条数据

/// </summary>

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

{

 BatchInsertAsync(objs).Wait();

}

 

/// <summary>

/// MongoDB C# Driver的Find方法,返回IFindFluent。手动输入collection name

/// </summary>

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

{

 if (database == null)

 {

  throw new Exception("没有指定数据库");

 }

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

 return collection.Find(filter, options);

}

 

/// <summary>

/// MongoDB C# Driver的Find方法,返回IFindFluent。采用类型T的完全限定名作为collection name

/// </summary>

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

{

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

}

 

/// <summary>

/// 取符合条件的数据 sort中多个排序条件逗号分隔,默认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>

/// 取符合条件的数据 sort中多个排序条件逗号分隔,默认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(&#39;,&#39;);

   for (var i = 0; i < sortList.Length; i++)

   {

    var sl = Regex.Replace(sortList[i].Trim(), @"\s+", " ").Split(&#39; &#39;);

    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)

 {

  //异常处理

 }

 return ret;

}

 

public List<T> Get<T>(List<Expression<Func<T, bool>>> conditions)

{

 return Get(conditions, 0, 0, null);

}
Copy after login

示例代码中只实现了插入和查询功能,后续会将完整代码上传

总结

本文只记录了MongoDB的最基本使用,后续会介绍副本级,主从自动备份等机制与实现方式,感兴趣的朋友们请继续关注脚本之家,谢谢大家对脚本之家的支持。

The above is the detailed content of Tutorial on how to use MongoDB in .Net. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Navicat's method to view MongoDB database password Navicat's method to view MongoDB database password Apr 08, 2025 pm 09:39 PM

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

Use Composer to solve the dilemma of recommendation systems: andres-montanez/recommendations-bundle Use Composer to solve the dilemma of recommendation systems: andres-montanez/recommendations-bundle Apr 18, 2025 am 11:48 AM

When developing an e-commerce website, I encountered a difficult problem: how to provide users with personalized product recommendations. Initially, I tried some simple recommendation algorithms, but the results were not ideal, and user satisfaction was also affected. In order to improve the accuracy and efficiency of the recommendation system, I decided to adopt a more professional solution. Finally, I installed andres-montanez/recommendations-bundle through Composer, which not only solved my problem, but also greatly improved the performance of the recommendation system. You can learn composer through the following address:

C# .NET: Exploring Core Concepts and Programming Fundamentals C# .NET: Exploring Core Concepts and Programming Fundamentals Apr 10, 2025 am 09:32 AM

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

What is the CentOS MongoDB backup strategy? What is the CentOS MongoDB backup strategy? Apr 14, 2025 pm 04:51 PM

Detailed explanation of MongoDB efficient backup strategy under CentOS system This article will introduce in detail the various strategies for implementing MongoDB backup on CentOS system to ensure data security and business continuity. We will cover manual backups, timed backups, automated script backups, and backup methods in Docker container environments, and provide best practices for backup file management. Manual backup: Use the mongodump command to perform manual full backup, for example: mongodump-hlocalhost:27017-u username-p password-d database name-o/backup directory This command will export the data and metadata of the specified database to the specified backup directory.

MongoDB and relational database: a comprehensive comparison MongoDB and relational database: a comprehensive comparison Apr 08, 2025 pm 06:30 PM

MongoDB and relational database: In-depth comparison This article will explore in-depth the differences between NoSQL database MongoDB and traditional relational databases (such as MySQL and SQLServer). Relational databases use table structures of rows and columns to organize data, while MongoDB uses flexible document-oriented models to better suit the needs of modern applications. Mainly differentiates data structures: Relational databases use predefined schema tables to store data, and relationships between tables are established through primary keys and foreign keys; MongoDB uses JSON-like BSON documents to store them in a collection, and each document structure can be independently changed to achieve pattern-free design. Architectural design: Relational databases need to pre-defined fixed schema; MongoDB supports

From Web to Desktop: The Versatility of C# .NET From Web to Desktop: The Versatility of C# .NET Apr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

Advanced C# .NET Tutorial: Ace Your Next Senior Developer Interview Advanced C# .NET Tutorial: Ace Your Next Senior Developer Interview Apr 08, 2025 am 12:06 AM

Interview with C# senior developer requires mastering core knowledge such as asynchronous programming, LINQ, and internal working principles of .NET frameworks. 1. Asynchronous programming simplifies operations through async and await to improve application responsiveness. 2.LINQ operates data in SQL style and pay attention to performance. 3. The CLR of the NET framework manages memory, and garbage collection needs to be used with caution.

How to encrypt data in Debian MongoDB How to encrypt data in Debian MongoDB Apr 12, 2025 pm 08:03 PM

Encrypting MongoDB database on a Debian system requires following the following steps: Step 1: Install MongoDB First, make sure your Debian system has MongoDB installed. If not, please refer to the official MongoDB document for installation: https://docs.mongodb.com/manual/tutorial/install-mongodb-on-debian/Step 2: Generate the encryption key file Create a file containing the encryption key and set the correct permissions: ddif=/dev/urandomof=/etc/mongodb-keyfilebs=512

See all articles