-
Notifications
You must be signed in to change notification settings - Fork 2
MongoDB Database Provider
Teuz edited this page Apr 3, 2025
·
1 revision
For easy integration with MongoDB, you can use the FeatureManagement.Database.MongoDB package.
This package provides:
- A default
FeatureStoreimplementation of theIFeatureStoreinterface, which can be extended as needed. - An
IMongoDBConnectionFactoryfor creating database connections with default implementation.
First, install the package:
dotnet add package FeatureManagement.Database.MongoDBUse the default MongoDBConnectionFactory and configure the services:
services.AddDatabaseFeatureManagement<FeatureStore>()
.UseMongoDB(options =>
{
options.ConnectionString = "mongodb://localhost:27017";
options.DatabaseName = "FeatureManagement";
options.FeaturesCollectionName = "Features";
});services.AddDatabaseFeatureManagement<FeatureStore>()
.UseMongoDB(Configuration.GetSection("MongoDBOptions"));With corresponding appsettings.json:
{
"MongoDBOptions": {
"ConnectionString": "mongodb://localhost:27017",
"DatabaseName": "FeatureManagement",
"FeaturesCollectionName": "Features"
}
}Implement your own MongoDB connection factory:
public class MyMongoDBConnectionFactory : IMongoDBConnectionFactory
{
private readonly IMongoClient _client;
private readonly string _databaseName;
public MyMongoDBConnectionFactory(string connectionString, string databaseName)
{
_client = new MongoClient(connectionString);
_databaseName = databaseName;
}
public IMongoDatabase GetDatabase()
{
return _client.GetDatabase(_databaseName);
}
public IMongoCollection<Feature> GetFeaturesCollection()
{
return GetDatabase().GetCollection<Feature>("CustomFeatures");
}
}Then register it with your services:
// Register custom factory
services.AddSingleton<IMongoDBConnectionFactory>(_ =>
new MyMongoDBConnectionFactory("mongodb://localhost:27017", "MyFeatureDb"));
// Use the registered factory
services.AddDatabaseFeatureManagement<FeatureStore>()
.UseMongoDB();MongoDB feature documents are structured as follows:
{
"_id": "ObjectId(\"60d5ec9f9c8a1c8e0c6e9c82\")",
"Name": "BetaFeature",
"RequirementType": 1,
"Settings": [
{
"_id": "ObjectId(\"60d5ec9f9c8a1c8e0c6e9c83\")",
"FilterType": "Percentage",
"Parameters": "{\"Value\":50}"
},
{
"_id": "ObjectId(\"60d5ec9f9c8a1c8e0c6e9c84\")",
"FilterType": "TimeWindow",
"Parameters": "{\"Start\":\"2023-01-01T00:00:00Z\",\"End\":\"2023-12-31T23:59:59Z\"}"
}
]
}Here's a complete example showing how to integrate MongoDB with feature management:
public void ConfigureServices(IServiceCollection services)
{
// Register MongoDB feature management
services.AddDatabaseFeatureManagement<FeatureStore>()
.UseMongoDB(options =>
{
options.ConnectionString = Configuration.GetConnectionString("MongoDb");
options.DatabaseName = "FeatureFlags";
options.FeaturesCollectionName = "Features";
})
.WithCacheService();
// Other service registrations...
}