I have been studying mongodb recently, and after searching on the Internet, I 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 how to use mongodb in .Net. Friends who need a tutorial on how to use MongoDB can refer to it. Let’s take a look below.
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 an object-oriented query language. It can almost implement most functions similar to single-table queries in relational databases, and it 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 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 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 installation under windows
The installation of MongoDB is very simple. After setting the installation path, keep Next until the installation is completed. The biggest pitfall is For the installation of MongoDB service, let’s talk about some configuration operations after MongoDB installation in detail
1. Create the database path (data directory), log path (logs directory), and log file (mongo.log file) in the root directory ), 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 #启用验证 需要用户名密码
After completing the above two steps, you can start MongoDB
Run the CMD input command (note the path of mongod)
mongod --config " D:\Program Files\mongodb\data \conf\mongo.conf"
3. Create and start the MongoDB service
Wouldn’t it be quite troublesome if you follow step 3 every time? Follow the following command to create and start the MongoDB service, and you can manage MongoDB through the windows service. Started and closed
mongod --config " D:\Program Files\mongodb\data \conf\mongo.conf" --install --serviceName "MongoDB" net start MongoDB
To test whether it is successful, you can enter http://localhost:27017/ in the browser. If the following picture appears, the service installation is successful
If you need to uninstall the MongoDB service and run it in CMD
mongod.exe --remove --serviceName "MongoDB"
After the preliminary preparation work is completed, you can start coding
How to use MongoDB in .net
First introduce MongoDB.Bson.dll, MongoDB.Driver.dll, MongoDB.Driver.Core into the project .dll I am using version 2.0. Now many articles introduce the use of version 1+. This is also the purpose of writing this article. After introducing the driver DLL, you can start coding.
Part of the code As follows
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(','); 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) { //异常处理 } return ret; } public List<T> Get<T>(List<Expression<Func<T, bool>>> conditions) { return Get(conditions, 0, 0, null); }
The above is the detailed content of Detailed explanation of how to use MongoDB in .Net. For more information, please follow other related articles on the PHP Chinese website!

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

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

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.