- 安装
Install-Package MongoDBDriver.AspNetCore
dotnet add package MongoDBDriver.AspNetCore
- 创建上下文类继承MongoDbContext
public class TestMongoDbContext : MongoDbContext
{
//对应注册AddMongoDbContext<TestMongoDbContext>("mongodb://localhost:27017/", "Test")
public TestMongoDbContext(string connectionString, string database) : base(connectionString, database)
{
}
//对应注册AddMongoDbContext<TestMongoDbContext>("mongodb://localhost:27017/", "Test", options => { })
public TestMongoDbContext(string database, MongoClientSettings settings) : base(database, settings)
{
}
//配置 MongoCollection
public IMongoCollection<Doc> Doc => GetCollection<Doc>(nameof(Doc));
}
- 注册 MongoDBDriver.AspNetCore
builder.Services.AddMongoDbContext<TestMongoDbContext>("mongodb://localhost:27017/", "Test");
//OR
builder.Services.AddMongoDbContext<TestMongoDbContext>("mongodb://localhost:27017/", "Test", options => { });
- 注入上下文
private readonly TestMongoDbContext _context;
public WeatherForecastController( TestMongoDbContext context)
{
_context = context;
}
[HttpGet(Name = "GetWeatherForecast")]
public void Get()
{
//添加数据
_context.Doc.InsertOne(new Doc { Title = "Test" });
}