在 ASP.NET Core 中使用 MongoDB 可以通过官方驱动 MongoDB.Driver
实现。以下是完整的集成步骤和示例代码:
dotnet add package MongoDB.Driver
{
"MongoDB": {
"ConnectionString": "mongodb://localhost:27017",
"DatabaseName": "MyAppDB"
}
}
// Program.cs
using MongoDB.Driver;
var builder = WebApplication.CreateBuilder(args);
// 注册 MongoDB 配置
builder.Services.Configure(
builder.Configuration.GetSection("MongoDB")
);
// 注册 IMongoDatabase 实例
builder.Services.AddSingleton(serviceProvider => {
var settings = serviceProvider.GetRequiredService>().Value;
var client = new MongoClient(settings.ConnectionString);
return client.GetDatabase(settings.DatabaseName);
});
// 自定义 MongoDB 上下文(可选)
builder.Services.AddScoped();
public class MongoDBSettings
{
public string ConnectionString { get; set; }
public string DatabaseName { get; set; }
}
// 自定义上下文类(可选)
public class MongoDBContext
{
private readonly IMongoDatabase _database;
public MongoDBContext(IMongoDatabase database)
{
_database = database;
}
public IMongoCollection GetCollection(string name)
{
return _database.GetCollection(name);
}
}
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
public class Product
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
[BsonElement("name")]
public string Name { get; set; }
[BsonElement("price")]
public decimal Price { get; set; }
}
public interface IProductRepository
{
Task> GetAllAsync();
Task GetByIdAsync(string id);
Task CreateAsync(Product product);
Task UpdateAsync(string id, Product product);
Task DeleteAsync(string id);
}
public class ProductRepository : IProductRepository
{
private readonly IMongoCollection _collection;
public ProductRepository(MongoDBContext context)
{
_collection = context.GetCollection("products");
}
public async Task> GetAllAsync()
{
return await _collection.Find(_ => true).ToListAsync();
}
public async Task GetByIdAsync(string id)
{
return await _collection.Find(p => p.Id == id).FirstOrDefaultAsync();
}
public async Task CreateAsync(Product product)
{
await _collection.InsertOneAsync(product);
}
public async Task UpdateAsync(string id, Product product)
{
await _collection.ReplaceOneAsync(p => p.Id == id, product);
}
public async Task DeleteAsync(string id)
{
await _collection.DeleteOneAsync(p => p.Id == id);
}
}
// 注册仓储
builder.Services.AddScoped();
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
private readonly IProductRepository _repository;
public ProductsController(IProductRepository repository)
{
_repository = repository;
}
[HttpGet]
public async Task GetAll()
{
var products = await _repository.GetAllAsync();
return Ok(products);
}
[HttpGet("{id}")]
public async Task GetById(string id)
{
var product = await _repository.GetByIdAsync(id);
return product == null ? NotFound() : Ok(product);
}
[HttpPost]
public async Task Create(Product product)
{
await _repository.CreateAsync(product);
return CreatedAtAction(nameof(GetById), new { id = product.Id }, product);
}
}
// 在仓储类构造函数中添加索引
var indexKeys = Builders.IndexKeys.Ascending(p => p.Name);
_collection.Indexes.CreateOne(new CreateIndexModel(indexKeys));
public async Task GetAveragePrice()
{
var pipeline = new BsonDocument[]
{
new BsonDocument("$group", new BsonDocument
{
{ "_id", BsonNull.Value },
{ "averagePrice", new BsonDocument("$avg", "$price") }
})
};
var result = await _collection.AggregateAsync(pipeline);
return result.First()["averagePrice"].AsDecimal;
}
连接池优化
var settings = MongoClientSettings.FromUrl(new MongoUrl(connectionString));
settings.MaxConnectionPoolSize = 100; // 默认 100
settings.MinConnectionPoolSize = 10;
var client = new MongoClient(settings);
超时设置
settings.ConnectTimeout = TimeSpan.FromSeconds(30);
settings.ServerSelectionTimeout = TimeSpan.FromSeconds(30);
Async
后缀方法IMongoCollection
或自定义仓储MongoException
app.UseExceptionHandler(errApp =>
{
errApp.Run(async context =>
{
var exception = context.Features.Get();
if (exception?.Error is MongoException)
{
await context.Response.WriteAsync("Database error");
}
});
});
appsettings.{Environment}.json
管理开发/生产环境配置通过以上步骤,即可在 ASP.NET Core 中高效集成 MongoDB,实现灵活的数据存储方案。根据业务需求扩展仓储模式或直接使用 IMongoCollection
进行操作。