文章目录
- 操作MongoDB
- 1 目标
- 2 步骤
- 2.1 安装依赖库
- 2.2 创建 MongoDB 配置和模型
- 2.3 配置 MongoDB 连接
- 2.4 创建 MongoDB 服务
- 2.5 创建控制器
- 2.6 运行
操作MongoDB
1 目标
使用DotNet实现操作MongoDB。
2 步骤
2.1 安装依赖库
dotnet add package MongoDB.Driver
2.2 创建 MongoDB 配置和模型
在 Models 文件夹中创建一个 Item.cs 文件:
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson;
namespace WebApplication1.Models
{
// 定义一个 Item 类,用于表示项目数据
// BsonIgnoreExtraElements表示忽略MongoDB其他字段
[BsonIgnoreExtraElements]
public class Item
{
// MongoDB中的文档ID字段
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
// 项目名称字段
[BsonElement("name")]
public string Name { get; set; }
// 项目描述字段
[BsonElement("description")]
public string Description { get; set; }
}
}
创建 MongoDBSettings.cs 文件以存储 MongoDB 配置信息:
namespace WebApplication1
{
/// <summary>
/// 用于存储MongoDB相关配置信息的类
/// </summary>
public class MongoDBSettings
{
/// <summary>
/// MongoDB连接字符串,用于连接到MongoDB服务器
/// </summary>
public string ConnectionString { get; set; }
/// <summary>
/// 数据库名称,指定要使用的数据库
/// </summary>
public string DatabaseName { get; set; }
/// <summary>
/// 集合名称,指定要使用的集合
/// </summary>
public string CollectionName { get; set; }
}
}
2.3 配置 MongoDB 连接
在 appsettings.json 文件中添加 MongoDB 配置:
{
"MongoDBSettings": {
"ConnectionString": "mongodb://localhost:27017",
"DatabaseName": "testdb",
"CollectionName": "items"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
在 Program.cs 文件中配置 MongoDB 服务:
using WebApplication1.Services;
using WebApplication1;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// 添加MongoDB相关
builder.Services.Configure<MongoDBSettings>(
builder.Configuration.GetSection("MongoDBSettings"));
builder.Services.AddSingleton<MongoDBService>();
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();
2.4 创建 MongoDB 服务
在 Services 文件夹中创建一个 MongoDBService.cs 文件:
using Microsoft.Extensions.Options;
using MongoDB.Driver;
using WebApplication1.Models;
namespace WebApplication1.Services
{
/// <summary>
/// 用于与MongoDB进行交互的服务类
/// </summary>
public class MongoDBService
{
private readonly IMongoCollection<Item> _itemsCollection;
/// <summary>
/// 构造函数,初始化MongoDB客户端、数据库和集合
/// </summary>
/// <param name="mongoDBSettings">MongoDB设置选项</param>
public MongoDBService(IOptions<MongoDBSettings> mongoDBSettings)
{
// 创建MongoDB客户端
var mongoClient = new MongoClient(
mongoDBSettings.Value.ConnectionString);
// 获取指定的数据库
var mongoDatabase = mongoClient.GetDatabase(
mongoDBSettings.Value.DatabaseName);
// 获取指定的集合
_itemsCollection = mongoDatabase.GetCollection<Item>(
mongoDBSettings.Value.CollectionName);
}
/// <summary>
/// 异步获取所有项目
/// </summary>
/// <returns>项目列表</returns>
public async Task<List<Item>> GetAsync() =>
await _itemsCollection.Find(_ => true).ToListAsync();
/// <summary>
/// 异步根据ID获取项目
/// </summary>
/// <param name="id">项目ID</param>
/// <returns>项目对象</returns>
public async Task<Item?> GetAsync(string id) =>
await _itemsCollection.Find(x => x.Id == id).FirstOrDefaultAsync();
/// <summary>
/// 异步创建新项目
/// </summary>
/// <param name="newItem">新项目对象</param>
/// <returns>异步任务</returns>
public async Task CreateAsync(Item newItem) =>
await _itemsCollection.InsertOneAsync(newItem);
/// <summary>
/// 异步更新项目
/// </summary>
/// <param name="id">项目ID</param>
/// <param name="updatedItem">更新后的项目对象</param>
/// <returns>异步任务</returns>
public async Task UpdateAsync(string id, Item updatedItem) =>
await _itemsCollection.ReplaceOneAsync(x => x.Id == id, updatedItem);
/// <summary>
/// 异步删除项目
/// </summary>
/// <param name="id">项目ID</param>
/// <returns>异步任务</returns>
public async Task RemoveAsync(string id) =>
await _itemsCollection.DeleteOneAsync(x => x.Id == id);
}
}
2.5 创建控制器
在 Controllers 文件夹中创建一个 ItemsController.cs 文件:
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
using System.Collections.Generic;
using System.Linq;
using WebApplication1.Services;
namespace WebApplication1.Controllers
{
/// <summary>
/// 处理与Item相关的API请求的控制器
/// </summary>
[ApiController]
[Route("api/[controller]")]
public class ItemsController : ControllerBase
{
private readonly MongoDBService _mongoDBService;
/// <summary>
/// 构造函数,初始化MongoDB服务
/// </summary>
/// <param name="mongoDBService">MongoDB服务实例</param>
public ItemsController(MongoDBService mongoDBService) =>
_mongoDBService = mongoDBService;
/// <summary>
/// 获取所有Item
/// </summary>
/// <returns>Item列表</returns>
[HttpGet]
public async Task<List<Item>> Get() =>
await _mongoDBService.GetAsync();
/// <summary>
/// 根据ID获取指定的Item
/// </summary>
/// <param name="id">Item的ID,长度为24</param>
/// <returns>指定的Item对象</returns>
[HttpGet("{id:length(24)}")]
public async Task<ActionResult<Item>> Get(string id)
{
var item = await _mongoDBService.GetAsync(id);
if (item is null)
{
return NotFound();
}
return item;
}
/// <summary>
/// 创建新的Item
/// </summary>
/// <param name="newItem">新的Item对象</param>
/// <returns>创建结果</returns>
[HttpPost]
public async Task<IActionResult> Post(Item newItem)
{
await _mongoDBService.CreateAsync(newItem);
return CreatedAtAction(nameof(Get), new { id = newItem.Id }, newItem);
}
/// <summary>
/// 更新指定的Item
/// </summary>
/// <param name="id">Item的ID,长度为24</param>
/// <param name="updatedItem">更新后的Item对象</param>
/// <returns>操作结果</returns>
[HttpPut("{id:length(24)}")]
public async Task<IActionResult> Update(string id, Item updatedItem)
{
var item = await _mongoDBService.GetAsync(id);
if (item is null)
{
return NotFound();
}
updatedItem.Id = item.Id;
await _mongoDBService.UpdateAsync(id, updatedItem);
return NoContent();
}
/// <summary>
/// 部分更新指定的Item
/// </summary>
/// <param name="id">Item的ID,长度为24</param>
/// <param name="updatedFields">需要更新的字段</param>
/// <returns>操作结果</returns>
[HttpPatch("{id:length(24)}")]
public async Task<IActionResult> PartialUpdate(string id, [FromBody] Item updatedFields)
{
var item = await _mongoDBService.GetAsync(id);
if (item is null)
{
return NotFound();
}
if (updatedFields.Name != null)
{
item.Name = updatedFields.Name;
}
if (updatedFields.Description != null)
{
item.Description = updatedFields.Description;
}
await _mongoDBService.UpdateAsync(id, item);
return NoContent();
}
/// <summary>
/// 删除指定的Item
/// </summary>
/// <param name="id">Item的ID,长度为24</param>
/// <returns>操作结果</returns>
[HttpDelete("{id:length(24)}")]
public async Task<IActionResult> Delete(string id)
{
var item = await _mongoDBService.GetAsync(id);
if (item is null)
{
return NotFound();
}
await _mongoDBService.RemoveAsync(id);
return NoContent();
}
}
}
2.6 运行
dotnet run