MongoDB · Create
Set up the service from the database's schema
The service set up from the database instead of by hand, in three scenarios: preload a collection at startup, create through the preloaded service, and Strict, where only the preloaded fields may be written.
Set up for this page
Besides the sample itself, it uses SampleContext.cs (the dbContext every sample is given); SampleOutput.cs (Step and Show, which print); SampleContext.Direct.cs (dbContext.Direct); MongoDirectHelper.cs (the checks behind dbContext.Direct), in the files below.
dbContext.Direct is the samples' own checking code on the plain driver, not part of ARX: leave it out of your application.
1 Preload at startup
Preload the lead collection once, at startup.
Already in scope: connectionString (string)
var catalog = await new ArxPreLoadTable(new ArxPreLoadTableRegister().PreLoadTable("lead")).LoadAsync(connectionString);
catalog.TryGetTable("lead", out var lead);
Console.WriteLine($"lead: id {lead.IdColumn}, keys {string.Join(", ", lead.Keys)}, fields {string.Join(", ", lead.Columns.Keys)}");
return catalog;Check it in the database
Run it in mongosh connected to the database, after the code has run.
db.getCollectionInfos({ name: "lead" })[0].options.validatorExpect: the $jsonSchema with email, full_name, score and captured_on.
2 Create through the preloaded service
Create through the preloaded service; a value of the wrong type is refused before MongoDB sees it.
Already in scope: connectionString (string), catalog (ArxSchemaCatalog)
var service = new ArxMongoDbService(connectionString, catalog);
var lead = new ArxEntity("lead");
lead["email"] = "lead-m701@example.com";
lead["full_name"] = "Kim Abercrombie";
lead["score"] = 72;
lead["captured_on"] = new DateTime(2026, 11, 9, 8, 0, 0, DateTimeKind.Utc);
await service.CreateAsync(lead);
Console.WriteLine("created lead-m701@example.com");
var wrong = new ArxEntity("lead");
wrong["email"] = "lead-m702@example.com";
wrong["score"] = "high";
try
{
await service.CreateAsync(wrong);
}
catch (ArxValidationException exception) when (exception.Code == ArxErrorCode.DataTypeMismatch)
{
Console.WriteLine(exception.Message);
}Check it in the database
Run it in mongosh connected to the database, after the code has run.
db.lead.find({ email: { $in: ["lead-m701@example.com", "lead-m702@example.com"] } })Expect: 1 document, lead-m701@example.com with score 72.
3 Strict
Strict: a field the preload didn't load is refused (ARX1018), so a typo can't add a field.
Already in scope: connectionString (string), catalog (ArxSchemaCatalog)
var service = new ArxMongoDbService(connectionString, catalog) { Strict = true };
var lead = new ArxEntity("lead");
lead["email"] = "lead-m703@example.com";
lead["scroe"] = 10;
try
{
await service.CreateAsync(lead);
}
catch (ArxValidationException exception) when (exception.Code == ArxErrorCode.NotPreloaded)
{
Console.WriteLine(exception.Message);
}Check it in the database
Run it in mongosh connected to the database, after the code has run.
db.lead.countDocuments({ email: "lead-m703@example.com" })Expect: 0.
Good to know
ArxPreLoadTable reads, once, each collection's id (ObjectId ids are generated strings), its unique indexes (as keys) and the field types of its $jsonSchema validator. A value of the wrong type is then refused before anything is sent (ARX4004). MongoDB has no foreign keys: declare lookups in the configure callback.
Run the complete sample
The code above comes from one program, built in a fresh project and run against the database. To run it yourself, here is every file and step.
The program, its files and how to run it
Run it locally
- .NET SDK: .NET SDK 10.0.100 or later 10.0.x (target
net10.0). - Create the project:
Terminal dotnet new console -n ArxSample -f net10.0 cd ArxSample - Install the packages:
Terminal dotnet add package ARX.SDK.MongoDb --version 1.0.0-rc.1 - Database: a MongoDB 7.0, a replica set (tested with 7.0.45, one node) database with the sample schema.
- Configuration: set
ARX_SAMPLES_MONGODBto its connection string. Nothing is hard-coded. - Source code: replace
Program.csand add the 5 other files below, with the file names shown. - Run it:
Terminal dotnet run - Expected output: below.
The files
Runs the sample. Generated for this page; it reads the connection string from the environment and first remakes the sample database from sample-schema.json.
using ArxSamples.MongoDb;
using ArxSamples.MongoDb.Operations.Create.AdvancedCases;
// The connection string comes from the environment, never from the code (see "Configure the connection").
var connectionString = Environment.GetEnvironmentVariable("ARX_SAMPLES_MONGODB")
?? throw new InvalidOperationException("Set the ARX_SAMPLES_MONGODB environment variable to your MongoDB connection string.");
var dbContext = new SampleContext(connectionString);
// Every run starts from the sample data: this deletes and makes again what sample-schema.json lists
// (save the file in the project folder, see Get started).
await dbContext.Direct.ResetAsync();
await new Advanced3_DynamicTableSchemaServiceSetup().RunAsync(dbContext);
The sample, as it is in the repository.
using ARX.SDK;
using ARX.SDK.MongoDb.Services;
using ARX.SDK.Services;
using static ArxSamples.MongoDb.SampleOutput;
namespace ArxSamples.MongoDb.Operations.Create.AdvancedCases;
/// <summary>
/// The service set up from the database instead of by hand, in three scenarios: preload a collection at startup, create
/// through the preloaded service, and Strict, where only the preloaded fields may be written.
/// </summary>
/// <remarks>
/// <c>ArxPreLoadTable</c> reads, once, each collection's id (ObjectId ids are generated strings), its unique indexes (as
/// keys) and the field types of its <c>$jsonSchema</c> validator. A value of the wrong type is then refused before
/// anything is sent (ARX4004). MongoDB has no foreign keys: declare lookups in the configure callback.
/// </remarks>
public sealed class Advanced3_DynamicTableSchemaServiceSetup : ISample
{
public string Name => "create-advanced-3-dynamic-table-schema-service-setup";
public string Title => "Set up the service from the database's schema";
public async Task RunAsync(SampleContext dbContext)
{
var catalog = await Scenario1_PreloadAtStartupAsync(dbContext.ConnectionString);
await Scenario2_CreateThroughThePreloadedServiceAsync(dbContext.ConnectionString, catalog);
await Scenario3_StrictAsync(dbContext.ConnectionString, catalog);
}
/// <summary>1. Preload the lead collection once, at startup.</summary>
private static async Task<ArxSchemaCatalog> Scenario1_PreloadAtStartupAsync(string connectionString)
{
Step("1. Preload at startup");
var catalog = await new ArxPreLoadTable(new ArxPreLoadTableRegister().PreLoadTable("lead")).LoadAsync(connectionString);
catalog.TryGetTable("lead", out var lead);
Show($"lead: id {lead.IdColumn}, keys {string.Join(", ", lead.Keys)}, fields {string.Join(", ", lead.Columns.Keys)}");
/* ===========================================================
* [DIRECT QUERY CHECK]
* -----------------------------------------------------------
* db.getCollectionInfos({ name: "lead" })[0].options.validator
* -- Expect: the $jsonSchema with email, full_name, score and captured_on.
* ===========================================================
*/
return catalog;
}
/// <summary>2. Create through the preloaded service; a value of the wrong type is refused before MongoDB sees it.</summary>
private static async Task Scenario2_CreateThroughThePreloadedServiceAsync(string connectionString, ArxSchemaCatalog catalog)
{
Step("2. Create through the preloaded service");
var service = new ArxMongoDbService(connectionString, catalog);
var lead = new ArxEntity("lead");
lead["email"] = "lead-m701@example.com";
lead["full_name"] = "Kim Abercrombie";
lead["score"] = 72;
lead["captured_on"] = new DateTime(2026, 11, 9, 8, 0, 0, DateTimeKind.Utc);
await service.CreateAsync(lead);
Show("created lead-m701@example.com");
var wrong = new ArxEntity("lead");
wrong["email"] = "lead-m702@example.com";
wrong["score"] = "high";
try
{
await service.CreateAsync(wrong);
}
catch (ArxValidationException exception) when (exception.Code == ArxErrorCode.DataTypeMismatch)
{
ShowError(exception);
}
/* ===========================================================
* [DIRECT QUERY CHECK]
* -----------------------------------------------------------
* db.lead.find({ email: { $in: ["lead-m701@example.com", "lead-m702@example.com"] } })
* -- Expect: 1 document, lead-m701@example.com with score 72.
* ===========================================================
*/
}
/// <summary>3. Strict: a field the preload didn't load is refused (ARX1018), so a typo can't add a field.</summary>
private static async Task Scenario3_StrictAsync(string connectionString, ArxSchemaCatalog catalog)
{
Step("3. Strict");
var service = new ArxMongoDbService(connectionString, catalog) { Strict = true };
var lead = new ArxEntity("lead");
lead["email"] = "lead-m703@example.com";
lead["scroe"] = 10;
try
{
await service.CreateAsync(lead);
}
catch (ArxValidationException exception) when (exception.Code == ArxErrorCode.NotPreloaded)
{
ShowError(exception);
}
/* ===========================================================
* [DIRECT QUERY CHECK]
* -----------------------------------------------------------
* db.lead.countDocuments({ email: "lead-m703@example.com" })
* -- Expect: 0.
* ===========================================================
*/
}
}
What every sample is given: the connection string (and the ISample interface the samples implement).
namespace ArxSamples.MongoDb;
/// <summary>One documentation sample: a scenario a real application has, shown end to end.</summary>
public interface ISample
{
/// <summary>The name to run it alone: <c>dotnet run -- <name></c>.</summary>
string Name { get; }
/// <summary>One line on what it shows.</summary>
string Title { get; }
Task RunAsync(SampleContext dbContext);
}
/// <summary>
/// What a sample is given. Every sample gets the connection string; the application's service and catalog
/// (SampleContext.Application.cs) and the plain MongoDB driver read-back helper (SampleContext.Direct.cs) live in their own
/// files, so a sample needs only the files it uses.
/// </summary>
public sealed partial class SampleContext
{
public SampleContext(string connectionString)
{
ConnectionString = connectionString;
}
public string ConnectionString { get; }
}
How the samples print: Step for each scenario, Show for what it did, ShowError for an error caught on purpose.
using ARX.SDK;
namespace ArxSamples.MongoDb;
/// <summary>How the samples print: a numbered step for each scenario, then what it did.</summary>
public static class SampleOutput
{
/// <summary>The start of a scenario: <c>Step("1. By the id Create returned")</c>.</summary>
public static void Step(string text) => Console.WriteLine($" > {text}");
/// <summary>What the scenario did.</summary>
public static void Show(string text) => Console.WriteLine($" {text}");
/// <summary>An ARX error the scenario caught on purpose.</summary>
public static void ShowError(ArxException exception)
=> Console.WriteLine($" caught {exception.GetType().Name}: {exception.Message}");
}
The plain MongoDB.Driver read-back helper, for the samples that show what MongoDB stored.
namespace ArxSamples.MongoDb;
/// <summary>The plain MongoDB driver outside the SDK, for the samples that show what MongoDB stored.</summary>
public sealed partial class SampleContext
{
private MongoDirectHelper? _direct;
/// <summary>The plain MongoDB driver outside the SDK, used only to reset the database and to show what was stored.</summary>
public MongoDirectHelper Direct => _direct ??= new MongoDirectHelper(ConnectionString);
}
Plain MongoDB.Driver, not part of ARX: reads rows back so a sample can show what MongoDB stored.
using MongoDB.Bson;
using MongoDB.Driver;
namespace ArxSamples.MongoDb;
/// <summary>
/// The plain MongoDB driver, outside the SDK: it resets the sample database from Schema/sample-schema.json and shows
/// what was stored. Samples never write through it.
/// </summary>
public sealed class MongoDirectHelper
{
private readonly IMongoDatabase _database;
public MongoDirectHelper(string connectionString)
{
var url = MongoUrl.Create(connectionString);
_database = new MongoClient(url).GetDatabase(url.DatabaseName ?? "arx_samples");
}
/// <summary>
/// The sample schema: Schema/sample-schema.json next to the program (the samples' own project), or sample-schema.json
/// in the project folder (a sample copied from its page, as Get started says).
/// </summary>
private static string SchemaPath()
{
var candidates = new[]
{
Path.Combine(AppContext.BaseDirectory, "Schema", "sample-schema.json"),
Path.Combine(Directory.GetCurrentDirectory(), "sample-schema.json"),
Path.Combine(Directory.GetCurrentDirectory(), "Schema", "sample-schema.json")
};
return candidates.FirstOrDefault(File.Exists)
?? throw new FileNotFoundException("sample-schema.json isn't in the project folder: download it from the Get started page and save it next to Program.cs.");
}
/// <summary>Drops the sample database and makes its collections, indexes and validators again.</summary>
public async Task ResetAsync()
{
var schema = BsonDocument.Parse(await File.ReadAllTextAsync(SchemaPath()));
foreach (var collection in schema["collections"].AsBsonArray.Select(x => x.AsBsonDocument))
{
var name = collection["name"].AsString;
// Only the collections the schema lists are dropped and made again: anything else in the database is left alone.
await _database.DropCollectionAsync(name);
var options = new CreateCollectionOptions<BsonDocument>();
if (collection.TryGetValue("validator", out var validator))
{
options.Validator = validator.AsBsonDocument;
}
await _database.CreateCollectionAsync(name, options);
foreach (var index in collection.GetValue("indexes", new BsonArray()).AsBsonArray.Select(x => x.AsBsonDocument))
{
var keys = index["keys"].AsBsonDocument;
var indexOptions = new CreateIndexOptions<BsonDocument> { Unique = index.GetValue("unique", false).AsBoolean };
if (index.GetValue("partial", false).AsBoolean)
{
indexOptions.PartialFilterExpression = new BsonDocument(keys.Names.Select(x => new BsonElement(x, new BsonDocument("$exists", true))));
}
await _database.GetCollection<BsonDocument>(name).Indexes.CreateOneAsync(new CreateIndexModel<BsonDocument>(keys, indexOptions));
}
}
}
/// <summary>The stored documents a filter finds, as MongoDB's JSON, one line each.</summary>
public async Task<IReadOnlyList<string>> FindAsync(string collection, string filterJson)
{
var documents = await _database.GetCollection<BsonDocument>(collection).Find(BsonDocument.Parse(filterJson)).ToListAsync();
return documents.Select(x => x.ToJson()).ToList();
}
}
Expected output
What dotnet run printed when the sample was verified, on a freshly created sample schema. Ids differ when the tables already hold rows.
> 1. Preload at startup
lead: id _id (String, generated), keys (email), fields email, full_name, score, captured_on
> 2. Create through the preloaded service
created lead-m701@example.com
caught ArxValidationException: ARX4004 DataTypeMismatch: Attribute 'score' on 'lead' is a String, but the preloaded schema says 'score' holds int (Int32).
> 3. Strict
caught ArxValidationException: ARX1018 NotPreloaded: Column 'scroe' of 'lead' isn't in the preloaded schema, and the service is Strict.