MongoDB · Create

Use fields named outside the name rule, through aliases

Use documents whose fields are named outside ARX's name rule, in three scenarios: declare an alias for each such field and create documents through them, read and query by the aliases, and see what is still refused: the field's own name in a call, and a field name MongoDB would read as a path.

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.

Before scenario 1 the sample runs this, so the service and the rows the scenarios use are there:

Set up
var schema = ArxSchemaCatalog.Create()
    .Table("legacy_customer", ArxIdColumn.Supplied<string>("customer_code"))
    .Alias("legacy_customer", "first_name", "first-name")
    .Alias("legacy_customer", "last_name", "last-name")
    .Alias("legacy_customer", "order_total", "Order Total")
    .Build();
var service = new ArxMongoDbService(connectionString, schema);

1 Create through the aliases

Create two customers: each attribute is written to the field its alias names.

Already in scope: service (ArxMongoDbService)

C#
var ana = new ArxEntity("legacy_customer");
ana["customer_code"] = "C-1001";
ana["first_name"] = "Ana";
ana["last_name"] = "Silva";
ana["order_total"] = 120.50m;

var id = await service.CreateAsync(ana);

var ben = new ArxEntity("legacy_customer");
ben["customer_code"] = "C-1002";
ben["first_name"] = "Ben";
ben["order_total"] = 75.00m;

await service.CreateAsync(ben);

Console.WriteLine($"created {id} and C-1002");

Check it in the database

javascript

Run it in mongosh connected to the database, after the code has run.

db.legacy_customer.find({ _id: { $in: ["C-1001", "C-1002"] } }, { "first-name": 1, "Order Total": 1 })

Expect: 2 documents: Ana with 120.50, Ben with 75.00.

2 Read and query by the aliases

Read a document by id and query by the aliases: every field comes back under its alias.

Already in scope: service (ArxMongoDbService)

C#
var ana = await service.RetrieveAsync("legacy_customer", ArxRecordId.Of("customer_code", "C-1001")) ?? throw new InvalidOperationException("The legacy_customer record isn't there.");

Console.WriteLine($"{ana["customer_code"]}: {ana["first_name"]} {ana["last_name"]}, total {ana["order_total"]}");

var query = new ArxQueryExpression("legacy_customer");
query.ColumnSet.AddColumns("first_name", "order_total");
query.Criteria.AddCondition("order_total", ArxConditionOperator.GreaterThan, 50m);
query.AddOrder("first_name", ArxOrderType.Descending);

var customers = await service.RetrieveMultipleAsync(query);

foreach (var customer in customers.Entities)
{
    Console.WriteLine($"{customer["first_name"]}: {customer["order_total"]}");
}

Check it in the database

javascript

Run it in mongosh connected to the database, after the code has run.

db.legacy_customer.find({ "Order Total": { $gt: 50 } }, { "first-name": 1, "Order Total": 1 }).sort({ "first-name": -1 })

Expect: Ben, then Ana.

3 What is still refused

The field's own name in a call, and an alias to a field name MongoDB reads as a path, are refused.

Already in scope: connectionString (string), service (ArxMongoDbService)

C#
var change = new ArxEntity("legacy_customer");
change["customer_code"] = "C-1002";
change["first-name"] = "Benjamin";

try
{
    await service.UpdateAsync(change);
}
catch (ArxException exception) when (exception.Code == ArxErrorCode.InvalidIdentifier)
{
    Console.WriteLine(exception.Message);
}

var dotted = new ArxMongoDbService(connectionString, ArxSchemaCatalog.Create()
    .Table("legacy_customer", ArxIdColumn.Supplied<string>("customer_code"))
    .Alias("legacy_customer", "order_total", "order.total")
    .Build());

var carl = new ArxEntity("legacy_customer");
carl["customer_code"] = "C-1003";
carl["order_total"] = 10m;

try
{
    await dotted.CreateAsync(carl);
}
catch (ArxException exception) when (exception.Code == ArxErrorCode.InvalidIdentifier)
{
    Console.WriteLine(exception.Message);
}

Check it in the database

javascript

Run it in mongosh connected to the database, after the code has run.

db.legacy_customer.find({ _id: { $in: ["C-1002", "C-1003"] } }, { "first-name": 1 })

Expect: 1 document, C-1002 with Ben (the update and the create were refused).

Good to know

ARX accepts only names of ASCII letters, digits and underscores. Documents written by other code may have fields such as first-name or Order Total: declare an alias for each in the schema catalog, .Alias(table, attribute, databaseName). Code uses the attribute; ARX writes, filters and sorts on the field, and reads it back as the attribute. The declared id is the document's _id, as always.

Only declared names pass, and a field name may not start with $ nor contain .: MongoDB reads those as an operator or a path.

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

  1. .NET SDK: .NET SDK 10.0.100 or later 10.0.x (target net10.0).
  2. Create the project:
    Terminal
    dotnet new console -n ArxSample -f net10.0
    cd ArxSample
  3. Install the packages:
    Terminal
    dotnet add package ARX.SDK.MongoDb --version 1.0.0-rc.1
  4. Database: a MongoDB 7.0, a replica set (tested with 7.0.45, one node) database with the sample schema.
  5. Configuration: set ARX_SAMPLES_MONGODB to its connection string. Nothing is hard-coded.
  6. Source code: replace Program.cs and add the 5 other files below, with the file names shown.
  7. Run it:
    Terminal
    dotnet run
  8. Expected output: below.

The files

Program.cs

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 Advanced5_FieldNamesThroughAliases().RunAsync(dbContext);
Advanced5_FieldNamesThroughAliases.cs

The sample, as it is in the repository.

using ARX.SDK;
using ARX.SDK.MongoDb.Services;
using ARX.SDK.Query;
using ARX.SDK.Services;
using static ArxSamples.MongoDb.SampleOutput;

namespace ArxSamples.MongoDb.Operations.Create.AdvancedCases;

/// <summary>
/// Use documents whose fields are named outside ARX's name rule, in three scenarios: declare an alias for each such field
/// and create documents through them, read and query by the aliases, and see what is still refused: the field's own name
/// in a call, and a field name MongoDB would read as a path.
/// </summary>
/// <remarks>
/// <para>ARX accepts only names of ASCII letters, digits and underscores. Documents written by other code may have fields
/// such as <c>first-name</c> or <c>Order Total</c>: declare an alias for each in the schema catalog,
/// <c>.Alias(table, attribute, databaseName)</c>. Code uses the attribute; ARX writes, filters and sorts on the field, and
/// reads it back as the attribute. The declared id is the document's <c>_id</c>, as always.</para>
/// <para>Only declared names pass, and a field name may not start with <c>$</c> nor contain <c>.</c>: MongoDB reads those
/// as an operator or a path.</para>
/// </remarks>
public sealed class Advanced5_FieldNamesThroughAliases : ISample
{
    public string Name => "create-advanced-5-field-names-through-aliases";

    public string Title => "Use fields named outside the name rule, through aliases";

    public async Task RunAsync(SampleContext dbContext)
    {
        var schema = ArxSchemaCatalog.Create()
            .Table("legacy_customer", ArxIdColumn.Supplied<string>("customer_code"))
            .Alias("legacy_customer", "first_name", "first-name")
            .Alias("legacy_customer", "last_name", "last-name")
            .Alias("legacy_customer", "order_total", "Order Total")
            .Build();

        var service = new ArxMongoDbService(dbContext.ConnectionString, schema);

        await Scenario1_CreateThroughTheAliasesAsync(service);

        await Scenario2_ReadAndQueryByTheAliasesAsync(service);

        await Scenario3_WhatIsStillRefusedAsync(service, dbContext);
    }

    /// <summary>1. Create two customers: each attribute is written to the field its alias names.</summary>
    private static async Task Scenario1_CreateThroughTheAliasesAsync(ArxMongoDbService service)
    {
        Step("1. Create through the aliases");

        var ana = new ArxEntity("legacy_customer");
        ana["customer_code"] = "C-1001";
        ana["first_name"] = "Ana";
        ana["last_name"] = "Silva";
        ana["order_total"] = 120.50m;

        var id = await service.CreateAsync(ana);

        var ben = new ArxEntity("legacy_customer");
        ben["customer_code"] = "C-1002";
        ben["first_name"] = "Ben";
        ben["order_total"] = 75.00m;

        await service.CreateAsync(ben);

        Show($"created {id} and C-1002");

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * db.legacy_customer.find({ _id: { $in: ["C-1001", "C-1002"] } }, { "first-name": 1, "Order Total": 1 })
         * -- Expect: 2 documents: Ana with 120.50, Ben with 75.00.
         * ===========================================================
         */
    }

    /// <summary>2. Read a document by id and query by the aliases: every field comes back under its alias.</summary>
    private static async Task Scenario2_ReadAndQueryByTheAliasesAsync(ArxMongoDbService service)
    {
        Step("2. Read and query by the aliases");

        var ana = await service.RetrieveAsync("legacy_customer", ArxRecordId.Of("customer_code", "C-1001")) ?? throw new InvalidOperationException("The legacy_customer record isn't there.");

        Show($"{ana["customer_code"]}: {ana["first_name"]} {ana["last_name"]}, total {ana["order_total"]}");

        var query = new ArxQueryExpression("legacy_customer");
        query.ColumnSet.AddColumns("first_name", "order_total");
        query.Criteria.AddCondition("order_total", ArxConditionOperator.GreaterThan, 50m);
        query.AddOrder("first_name", ArxOrderType.Descending);

        var customers = await service.RetrieveMultipleAsync(query);

        foreach (var customer in customers.Entities)
        {
            Show($"{customer["first_name"]}: {customer["order_total"]}");
        }

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * db.legacy_customer.find({ "Order Total": { $gt: 50 } }, { "first-name": 1, "Order Total": 1 }).sort({ "first-name": -1 })
         * -- Expect: Ben, then Ana.
         * ===========================================================
         */
    }

    /// <summary>3. The field's own name in a call, and an alias to a field name MongoDB reads as a path, are refused.</summary>
    private static async Task Scenario3_WhatIsStillRefusedAsync(ArxMongoDbService service, SampleContext dbContext)
    {
        Step("3. What is still refused");

        var change = new ArxEntity("legacy_customer");
        change["customer_code"] = "C-1002";
        change["first-name"] = "Benjamin";

        try
        {
            await service.UpdateAsync(change);
        }
        catch (ArxException exception) when (exception.Code == ArxErrorCode.InvalidIdentifier)
        {
            ShowError(exception);
        }

        var dotted = new ArxMongoDbService(dbContext.ConnectionString, ArxSchemaCatalog.Create()
            .Table("legacy_customer", ArxIdColumn.Supplied<string>("customer_code"))
            .Alias("legacy_customer", "order_total", "order.total")
            .Build());

        var carl = new ArxEntity("legacy_customer");
        carl["customer_code"] = "C-1003";
        carl["order_total"] = 10m;

        try
        {
            await dotted.CreateAsync(carl);
        }
        catch (ArxException exception) when (exception.Code == ArxErrorCode.InvalidIdentifier)
        {
            ShowError(exception);
        }

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * db.legacy_customer.find({ _id: { $in: ["C-1002", "C-1003"] } }, { "first-name": 1 })
         * -- Expect: 1 document, C-1002 with Ben (the update and the create were refused).
         * ===========================================================
         */
    }
}
SampleContext.cs

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 -- &lt;name&gt;</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; }
}
SampleOutput.cs

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}");
}
SampleContext.Direct.cs

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);
}
MongoDirectHelper.cs

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.

Output
  > 1. Create through the aliases
      created C-1001 and C-1002
  > 2. Read and query by the aliases
      C-1001: Ana Silva, total 120.50
      Ben: 75.00
      Ana: 120.50
  > 3. What is still refused
      caught ArxValidationException: ARX1003 InvalidIdentifier: Attribute name 'first-name' is not a valid name. Use ASCII letters, digits and underscores, starting with a letter or underscore, at most 120 characters. A field named otherwise is used through an alias declared in the schema catalog: .Alias(table, attribute, databaseName).
      caught ArxValidationException: ARX1003 InvalidIdentifier: The database name 'order.total' of alias 'order_total' of 'legacy_customer' starts with '$' or has a '.': MongoDB reads those as an operator or a path.