MongoDB · Update

Update one record

The smallest update, in three scenarios: by the id Create returned, clearing a value, and a record that isn't there.

Set up for this page

The scenarios build on the sample application: SampleContext.cs (the dbContext every sample is given); SampleOutput.cs (Step and Show, which print); SampleContext.Application.cs (dbContext.Service, the application's ARX service); SampleCatalog.cs (the tables' ids, keys, lookups and display names); SampleContext.Direct.cs (dbContext.Direct); MongoDirectHelper.cs (the checks behind dbContext.Direct).

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 account = new ArxEntity("account");
account["name"] = "Fourth Coffee";
account["account_number"] = "ACC-M801";
account["employee_count"] = 40;
account["website"] = "https://fourthcoffee.example";
var id = await service.CreateAsync(account);

1 By the id Create returned

Give the entity the id CreateAsync returned, and only the fields to change.

Already in scope: service (ArxMongoDbService), id (ArxRecordId)

C#
var change = new ArxEntity("account") { RecordId = id };
change["employee_count"] = 55;

int changed = await service.UpdateAsync(change);

Console.WriteLine($"{changed} document changed");

Check it in the database

javascript

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

db.account.find({ account_number: "ACC-M801" }, { name: 1, employee_count: 1 })

Expect: 1 document, Fourth Coffee, employee_count 55.

2 Clear a value

Null stores null: the field stays, empty.

Already in scope: service (ArxMongoDbService), id (ArxRecordId)

C#
var change = new ArxEntity("account") { RecordId = id };
change["website"] = null;

await service.UpdateAsync(change);

Console.WriteLine("website cleared");

Check it in the database

javascript

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

db.account.find({ account_number: "ACC-M801" }, { website: 1 })

Expect: 1 document, website null.

3 A record that isn't there

An id no document has: ARX2002.

Already in scope: service (ArxMongoDbService)

C#
var change = new ArxEntity("account") { RecordId = ArxRecordId.Of("account_id", "64b7f0c2a1b2c3d4e5f60718") };
change["employee_count"] = 1;

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

Check it in the database

javascript

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

db.account.countDocuments({ _id: ObjectId("64b7f0c2a1b2c3d4e5f60718") })

Expect: 0.

Good to know

Only the attributes you set are written ($set); a field left out keeps its value; an attribute set to null is stored as null. Nothing matched is ARX2002. A document's _id can't change in MongoDB.

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: add the files of the sample application this sample uses (SampleContext.cs, SampleOutput.cs, SampleContext.Application.cs, SampleCatalog.cs, SampleContext.Direct.cs, MongoDirectHelper.cs), then replace Program.cs and add the other file 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.Update.Basics;

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

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.Update.Basics;

/// <summary>
/// The smallest update, in three scenarios: by the id Create returned, clearing a value, and a record that isn't there.
/// </summary>
/// <remarks>
/// Only the attributes you set are written (<c>$set</c>); a field left out keeps its value; an attribute set to null is
/// stored as null. Nothing matched is ARX2002. A document's <c>_id</c> can't change in MongoDB.
/// </remarks>
public sealed class Basic1_UpdateOneRecord : ISample
{
    public string Name => "update-basics-1-update-one-record";

    public string Title => "Update one record";

    public async Task RunAsync(SampleContext dbContext)
    {
        var account = new ArxEntity("account");
        account["name"] = "Fourth Coffee";
        account["account_number"] = "ACC-M801";
        account["employee_count"] = 40;
        account["website"] = "https://fourthcoffee.example";
        var id = await dbContext.Service.CreateAsync(account);

        await Scenario1_ByTheIdCreateReturnedAsync(dbContext.Service, id);

        await Scenario2_ClearAValueAsync(dbContext.Service, id);

        await Scenario3_ARecordThatIsntThereAsync(dbContext.Service);
    }

    /// <summary>1. Give the entity the id CreateAsync returned, and only the fields to change.</summary>
    private static async Task Scenario1_ByTheIdCreateReturnedAsync(ArxMongoDbService service, ArxRecordId id)
    {
        Step("1. By the id Create returned");

        var change = new ArxEntity("account") { RecordId = id };
        change["employee_count"] = 55;

        int changed = await service.UpdateAsync(change);

        Show($"{changed} document changed");

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * db.account.find({ account_number: "ACC-M801" }, { name: 1, employee_count: 1 })
         * -- Expect: 1 document, Fourth Coffee, employee_count 55.
         * ===========================================================
         */
    }

    /// <summary>2. Null stores null: the field stays, empty.</summary>
    private static async Task Scenario2_ClearAValueAsync(ArxMongoDbService service, ArxRecordId id)
    {
        Step("2. Clear a value");

        var change = new ArxEntity("account") { RecordId = id };
        change["website"] = null;

        await service.UpdateAsync(change);

        Show("website cleared");

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * db.account.find({ account_number: "ACC-M801" }, { website: 1 })
         * -- Expect: 1 document, website null.
         * ===========================================================
         */
    }

    /// <summary>3. An id no document has: ARX2002.</summary>
    private static async Task Scenario3_ARecordThatIsntThereAsync(ArxMongoDbService service)
    {
        Step("3. A record that isn't there");

        var change = new ArxEntity("account") { RecordId = ArxRecordId.Of("account_id", "64b7f0c2a1b2c3d4e5f60718") };
        change["employee_count"] = 1;

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

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * db.account.countDocuments({ _id: ObjectId("64b7f0c2a1b2c3d4e5f60718") })
         * -- Expect: 0.
         * ===========================================================
         */
    }
}

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. By the id Create returned
      1 document changed
  > 2. Clear a value
      website cleared
  > 3. A record that isn't there
      caught ArxException: ARX2002 RecordNotFound: Update of 'account': no document matched the entity's id (field account_id).