


##1. Preface and introduction to MongoDB##Recently While integrating my own framework, I refactored the simplest CRUD of MongoDBD as a component and integrated it into the asp.net core project. Of course, this article does not explain the cluster deployment of mongodb. I will share it when I have the opportunity.
First of all, we see in MongoDB’s official documentation that MongoDb’s 2.4 or above For .Net driver supports .Net Core 2.0.
Regarding MongoDB, I think everyone should be familiar with it, and have heard of it even if they have not used it.
ASP.NET video tutorial#1. What is mongodb?
MongoDB is a database based on distributed file storage. It provides scalable and high-performance data storage solutions for web applications. It is a product between relational database and non-relational database. It is non-relational. The most feature-rich database. It is a powerful tool for data processing.
2. What are relational databases and non-relational databases?Relational database: The sqlserver, mysql, etc. we have used are all relational databases, and relational databases follow the ACID principle and have strict consistency.
Non-relational database: Also called NoSQL, it is used to store very large-scale data. These types of data storage do not require a fixed model and can be expanded horizontally without redundant operations.
3. RDBMS VS NoSQLRDBMS:
Highly organized structured data
Structured query language
Data and relationships are stored in separate tables
Strict consistency
Basic transactions
NoSQL:
No declarative query language
Key-value pair storage, column storage, document storage, etc.
Eventual consistency
Unstructured and unpredictable data
CAP theorem, high availability, High performance, high scalability
I believe that at this point, sharp-eyed students should have noticed the CAP theorem and eventual consistency, and will definitely think of distributed systems. I give you a big thumbs up here. It can be perfectly combined with nosql in a distributed system to improve our performance.
4. Introduce some concepts of RDBMS and Mongodb, which will help everyone understand
Translate, as follows:
2. Asp.net core integrates mongoDB
1. For the convenience of demonstration I downloaded the windows version of mongodb serverYou can go to the official website to download it yourself, and then for the visual interface, I used the tool Robo 3T. A very simple and beautiful visualization tool. Recommended for everyone to use.
After the installation is completed, you will see the mongodb server in the windows service
Then we open Robo 3T and connect our mongodb.
The first step: I create a new Core2 .0 class library
introduces the "MongoDB.Driver" nuget package.
Then extended the extension method of Services in Startup.cs
//扩展方法public static class ServiceCollectionExtensions { public static void AddMongoDB(this IServiceCollection services, IConfiguration configuration) { services.Configure<Settings>(options => { options.ConnectionString = configuration.GetSection("MongoConnection:ConnectionString").Value; options.Database = configuration.GetSection("MongoConnection:Database").Value; }); } }The second step: Refactor the CRUD class that encapsulates mongodb. You can encapsulate it yourself here and only display it. Search and add.
public class MongoDBBase
{
private readonly IMongoDatabase _database = null;
public MongoDBBase(string connectionString, string databaseName)
{
var client = new MongoClient(connectionString);
if (client != null)
{
_database = client.GetDatabase(databaseName);
}
}
#region SELECT
/// <summary>
/// 根据查询条件,获取数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="id"></param>
/// <returns></returns>
public List<T> GetList<T>(Expression<Func<T, bool>> conditions = null)
{
var collection = _database.GetCollection<T>(typeof(T).Name);
if (conditions != null)
{
return collection.Find(conditions).ToList();
}
return collection.Find(_ => true).ToList();
}#endregion
#region INSERT/// <summary>
/// 插入多条数据,数据用list表示
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
public List<T> InsertMany<T>(List<T> list)
{
var collection = _database.GetCollection<T>(typeof(T).Name);
collection.InsertMany(list);
return list;
}
#endregion
}
Add mongodb to appsetting.json in the project Connection string: I use a custom data name testdb here. When inserting into mongodb, the database, collection and document will be automatically created. Then look down
"MongoConnection": { //mongodb数据库连接 "ConnectionString": "mongodb://127.0.0.1:27017", "Database": "testdb", "IsSSL": true },Step 4: Create a new mongodb test controller, showing the interface for inserting single and multiple items and querying.
[Produces("application/json")]
[Route("api/MongoDB/[action]")]
public class MongoDBController : Controller
{
private readonly MongoDBBase _context = null;
public MongoDBController(IOptions<Settings> settings)
{
_context = new MongoDBBase(settings.Value.ConnectionString, settings.Value.Database);
}
[HttpGet]
public IActionResult AddList()
{
List<MongoDBPostTest> list = new List<MongoDBPostTest>()
{
new MongoDBPostTest()
{
Id = "2",
Body = "Test note 3",
UpdatedOn = DateTime.Now,
UserId = 1,
HeaderImage = new NoteImage
{
ImageSize = 10,
Url = "http://localhost/image1.png",
ThumbnailUrl = "http://localhost/image1_small.png"
}
},
new MongoDBPostTest()
{
Id = "3",
Body = "Test note 4",
UpdatedOn = DateTime.Now,
UserId = 1,
HeaderImage = new NoteImage
{
ImageSize = 14,
Url = "http://localhost/image3.png",
ThumbnailUrl = "http://localhost/image3_small.png"
}
}
};
try
{
_context.InsertMany(list);
}
catch (Exception ex)
{
throw;
}
return Ok("成功");
}
[HttpGet]
public Result<List<MongoDBPostTest>> SelectSingle()
{
//无条件
var list = _context.GetList<MongoDBPostTest>();
//有条件
//var list = _context.GetList<MongoDBPostTest>(a => a.Id == "1");
//得到单条数据,无条件
//var list = _context.GetSingle<MongoDBPostTest>();
//得到单条数据,有条件
//var list = _context.GetSingle<MongoDBPostTest>(a => a.Id == "3");
ObjectId internalId = _context.GetInternalId("5bbf41651d3b66668cbb5bfc");
var a = _context.GetSingle<MongoDBPostTest>(note => note.Id == "5bbf41651d3b66668cbb5bfc" || note.InternalId == internalId);
return ResHelper.Suc(1, list, "成功");
}
}
Test class
public class MongoDBPostTest { [BsonId] // standard BSonId generated by MongoDb public ObjectId InternalId { get; set; } public string Id { get; set; } public string Body { get; set; } = string.Empty; [BsonDateTimeOptions] public DateTime UpdatedOn { get; set; } = DateTime.Now; public NoteImage HeaderImage { get; set; } public int UserId { get; set; } = 0; } public class NoteImage { public string Url { get; set; } = string.Empty; public string ThumbnailUrl { get; set; } = string.Empty; public long ImageSize { get; set; } = 0L; }Step 5: Run the project and execute it.
Let’s insert multiple pieces of data and the execution is successful.
Then we looked at the database and found that a testdb database has been generated, which contains our data content
Then we perform the following query operations: return the data we just inserted.
Note: There is a pitfall to be solved here, that is, the time stored in mongodb is UTC, which will be different from our local The time difference is 8 hours. Therefore, special processing time is required here.
3. Summary
At this point, the simple use of mongodb has been demonstrated. Later, you can expand it according to the official documents, and then expand it further. , you will find it more and more interesting. thanks for your support. Thank you.
The above is the detailed content of Learn the complete steps to integrate MongoDB with asp.net core. For more information, please follow other related articles on the PHP Chinese website!

Microsoft的Windows112022Update(22H2)默认启用CoreIsolation的内存完整性保护。但是,如果您运行的是旧版本的操作系统,例如Windows112022Update(22H1),则需要手动打开此功能。在Windows11中开启CoreIsolation的内存完整性功能对于不了解核心隔离的用户,这是一个安全过程,旨在通过将Windows上的基本核心活动隔离在内存中来保护它们免受恶意程序的侵害。该进程与内存完整性功能相结合,可确保

电脑中core有两种意思:1、核心,也即内核,是CPU最重要的组成部分,CPU所有的计算、接受存储命令、处理数据都由核心执行;2、酷睿,core是英特尔的处理器名称,酷睿是英特尔公司继奔腾处理器之后推出的处理器品牌,目前已经发布了十二代酷睿处理器。

mongodb php扩展没有的解决办法:1、在linux中执行“$ sudo pecl install mongo”命令来安装MongoDB的PHP扩展驱动;2、在window中,下载php mongodb驱动二进制包,然后在“php.ini”文件中配置“extension=php_mongo.dll”即可。

Redis和MongoDB都是流行的开源NoSQL数据库,但它们的设计理念和使用场景有所不同。本文将重点介绍Redis和MongoDB的区别和使用场景。Redis和MongoDB简介Redis是一个高性能的数据存储系统,常被用作缓存和消息中间件。Redis以内存为主要存储介质,但它也支持将数据持久化到磁盘上。Redis是一款键值数据库,它支持多种数据结构(例

php7.0安装mongo扩展的方法:1、创建mongodb用户组和用户;2、下载mongodb源码包,并将源码包放到“/usr/local/src/”目录下;3、进入“src/”目录;4、解压源码包;5、创建mongodb文件目录;6、将文件复制到“mongodb/”目录;7、创建mongodb配置文件并修改配置即可。

MongoDB作为一款流行的NoSQL数据库,已经被广泛应用于各种大型Web应用和企业级应用中。而PHP语言也作为一种流行的Web编程语言,与MongoDB的结合也变得越来越重要。在本文中,我们将会学习如何使用PHP语言操作MongoDB数据库进行增删查改的操作。
![如何修复 Windows 11 / 10 中的处理器热跳闸错误 [修复]](https://img.php.cn/upload/article/000/000/164/168169038621890.png)
大多数设备(例如笔记本电脑和台式机)长期被年轻游戏玩家和编码人员频繁使用。由于应用程序过载,系统有时会挂起。这使用户被迫关闭他们的系统。这主要发生在安装和玩重度游戏的玩家身上。当系统在强制关闭后尝试启动时,它会在黑屏上抛出一个错误,如下所示:以下是在此引导期间检测到的警告。这些可以在事件日志页面的设置中查看。警告:处理器热跳闸。按任意键继续。..当台式机或笔记本电脑的处理器温度超过其阈值温度时,总是会抛出这些类型的警告消息。下面列出了在Windows系统上发生这种情况的原因。许多繁重的应用程序在

自定义Appender非常简单,继承一下AppenderBase类即可。可以看到有个AppenderBase,有个UnsynchronizedAppenderBase,还有个AsyncAppenderBase继承了UnsynchronizedAppenderBase。从名字就能看出来区别,异步的、普通的、不加锁的。我们定义一个MongoDBAppender继承UnsynchronizedAppenderBasepublicclassMongoDBAppenderextendsUnsynchron


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

Zend Studio 13.0.1
Powerful PHP integrated development environment

Atom editor mac version download
The most popular open source editor

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver Mac version
Visual web development tools
