一、MongoDB是什么?
MongoDB 是一个开源的、可扩展的、跨平台的、面向文档的非关系型数据库,它由 C++ 语言编写,旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。
二、使用步骤
1.安装驱动
install-package MongoDB.Driver
2.设置连接字符串、配置类
在appsettings.json中设置mongodb服务器地址、数据库
"MongoDbSetting": {
"Connection": "mongodb://localhost:27017",
"Database": "Test"
}
建立相应的配置类
public class MongoDbSetting:IMongoDbSetting
{
public string Connection { get; set; }
public string Database { get; set; }
}
public interface IMongoDbSetting
{
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 float Price { get; set; }
public DateTime 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
原文地址:https://blog.csdn.net/qq_42335551/article/details/134813747
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_47734.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。