目录
一、MongoDB是什么?
二、使用步骤
1.安装驱动
2.设置连接字符串、配置类
3.建立实体类
4.服务层
5.在Program添加服务
6.在Controller注入服务
总结
一、MongoDB是什么?
MongoDB 是一个开源的、可扩展的、跨平台的、面向文档的非关系型数据库,它由 C++ 语言编写,旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。
二、使用步骤
1.安装驱动
代码如下:
install-pack MongoDB.Driver
2.设置连接字符串、配置类
在appsettings.json中设置mongodb服务器地址、数据库
代码如下(示例):
"MongoDbSetting": {"Connection": "mongodb://localhost:27017","Database": "Test"}
建立相应的配置类
public class MongoDbSetting{public string Connection { get; set; }public string Database { get; set; }}
3.建立实体类
代码如下(示例):
public class Book{[BsonRepresentation(BsonType.ObjectId)]public string Id { get; set; }public string AuthorName { get; set; }public string Price { get; set; }public string PubTime { get; set; }public string Title { get; set; }}
4.服务层
代码如下(示例):
public class BookService{private readonly IMongoCollection<Book> _mongDb;public BookService(IMongoDbSetting setting){var client = new MongoClient(setting.Connection);var database = client.GetDatabase(setting.Database);_mongDb = database.GetCollection<Book>(nameof(Book));}/// <summary>/// 新增/// </summary>/// <param name="model"></param>/// <returns></returns>public Book Insert(Book model){_mongDb.InsertOne(model);return model;}/// <summary>/// 编辑/// </summary>/// <param name="id"></param>/// <param name="model"></param>public void Update(Book model){_mongDb.ReplaceOne(m => m.Id == model.Id, model);}/// <summary>/// 删除/// </summary>/// <param name="model"></param>public void Delete(Book model){_mongDb.DeleteOne(m => m.Id == model.Id);}/// <summary>/// 获取某一个对象/// </summary>/// <param name="id"></param>/// <returns></returns>public Book Get(string id){return _mongDb.Find<Book>(book => book.Id == id).FirstOrDefault();}/// <summary>/// 查询/// </summary>/// <param name="PageIndex"></param>/// <param name="PageSize"></param>/// <returns></returns>public List<Book> GetPageList(int PageIndex = 1, int PageSize = 10){//设置排序字段var sort = Builders<Book>.Sort.Descending(it => it.PubTime);return _mongDb.Find<Book>(b => true).Sort(sort).Skip((PageIndex - 1) * PageSize).Limit(PageSize).ToList();}}
5.在Program添加服务
代码如下(示例):
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using MyApI;var builder = WebApplication.CreateBuilder(args);// Add services to the container.#region 配置mongodb
builder.Services.Configure<MongoDbSetting>(builder.Configuration.GetSection(nameof(MongoDbSetting)));
builder.Services.AddSingleton<IMongoDbSetting>(sp => sp.GetRequiredService<IOptions<MongoDbSetting>>().Value);
builder.Services.AddSingleton<BookService>();
#endregion builder.Services.Configure<ApiBehaviorOptions>((o) =>
{o.SuppressModelStateInvalidFilter = true;
});
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();var app = builder.Build();// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{app.UseSwagger();app.UseSwaggerUI();
}app.UseAuthorization();app.MapControllers();app.Run();
6.在Controller注入服务
注入服务有三种方式(构造函数、属性、方法)通常一般选择构造函数的方式注入
在BookController中注入BookService 服务
代码如下(示例):
[Route("api/[controller]/[action]")][ApiController]public class BookController : ControllerBase{private readonly BookService _bookService;public BookController(BookService bookService) {_bookService=bookService;} [HttpPost]public ActionResult Insert(Book model){return new JsonResult(_bookService.Insert(model));}[HttpPost]public ActionResult Update(Book model){_bookService.Update(model);return NoContent();}[HttpPost]public ActionResult Delete(Book model){_bookService.Delete(model);return NoContent();}[HttpGet]public ActionResult Get(string id){return new JsonResult(_bookService.Get(id));}[HttpGet]public ActionResult GetPageList(int PageIndex = 1, int PageSize = 10){return new JsonResult(_bookService.GetPageList(PageIndex, PageSize));}}
总结
以上是我在.net core 对MongoDB数据库简单的使用
更多的使用查看官方文档MongoDB C# Driver — C#/.NET