MongoDB · Delete

Choose how the documents are found

Delete by a key or by any fields, in three scenarios: a compound key, every document with a field's value, and RequireSingleRow, which refuses to delete several.

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
foreach (var (region, sku) in new[] { ("PT", "SKU-M911"), ("PT", "SKU-M912"), ("ES", "SKU-M911") })
{
    var price = new ArxEntity("price_list");
    price["region"] = region;
    price["sku"] = sku;
    price["unit_price"] = 10m;
    price["batch"] = "M91";
    await service.CreateAsync(price);
}

1 By a compound key

The price of SKU-M911 in PT, by the region and SKU together.

Already in scope: service (ArxMongoDbService)

C#
var match = new ArxEntity("price_list");
match["region"] = "PT";
match["sku"] = "SKU-M911";

int deleted = await service.DeleteAsync(match, new ArxDeleteOptions { Match = ArxMatch.Key("region", "sku") });

Console.WriteLine($"{deleted} price deleted");

Check it in the database

javascript

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

db.price_list.find({ batch: "M91" }, { region: 1, sku: 1 })

Expect: 2 documents: PT SKU-M912, ES SKU-M911.

2 Require exactly one

RequireSingleRow with a field two documents share: ARX2003, nothing deleted.

Already in scope: service (ArxMongoDbService)

C#
var match = new ArxEntity("price_list");
match["batch"] = "M91";

try
{
    await service.DeleteAsync(match, new ArxDeleteOptions { Match = ArxMatch.Columns("batch"), RequireSingleRow = true });
}
catch (ArxException exception) when (exception.Code == ArxErrorCode.MultipleRecordsMatched)
{
    Console.WriteLine(exception.Message);
}

Check it in the database

javascript

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

db.price_list.countDocuments({ batch: "M91" })

Expect: 2.

3 By any fields

Every price of the batch.

Already in scope: service (ArxMongoDbService)

C#
var match = new ArxEntity("price_list");
match["batch"] = "M91";

int deleted = await service.DeleteAsync(match, new ArxDeleteOptions { Match = ArxMatch.Columns("batch") });

Console.WriteLine($"{deleted} prices deleted");

Check it in the database

javascript

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

db.price_list.countDocuments({ batch: "M91" })

Expect: 0.

Good to know

Finding nothing is a normal outcome (0) unless RequireSingleRow is on; then it is ARX2002, and several ARX2003.

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.Delete.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 Basic2_HowToFindTheRows().RunAsync(dbContext);
Basic2_HowToFindTheRows.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.Delete.Basics;

/// <summary>
/// Delete by a key or by any fields, in three scenarios: a compound key, every document with a field's value, and
/// RequireSingleRow, which refuses to delete several.
/// </summary>
/// <remarks>Finding nothing is a normal outcome (0) unless RequireSingleRow is on; then it is ARX2002, and several ARX2003.</remarks>
public sealed class Basic2_HowToFindTheRows : ISample
{
    public string Name => "delete-basics-2-how-to-find-the-rows";

    public string Title => "Choose how the documents are found";

    public async Task RunAsync(SampleContext dbContext)
    {
        foreach (var (region, sku) in new[] { ("PT", "SKU-M911"), ("PT", "SKU-M912"), ("ES", "SKU-M911") })
        {
            var price = new ArxEntity("price_list");
            price["region"] = region;
            price["sku"] = sku;
            price["unit_price"] = 10m;
            price["batch"] = "M91";
            await dbContext.Service.CreateAsync(price);
        }

        await Scenario1_ByACompoundKeyAsync(dbContext.Service);

        await Scenario2_RequireOneAsync(dbContext.Service);

        await Scenario3_ByAnyFieldsAsync(dbContext.Service);
    }

    /// <summary>1. The price of SKU-M911 in PT, by the region and SKU together.</summary>
    private static async Task Scenario1_ByACompoundKeyAsync(ArxMongoDbService service)
    {
        Step("1. By a compound key");

        var match = new ArxEntity("price_list");
        match["region"] = "PT";
        match["sku"] = "SKU-M911";

        int deleted = await service.DeleteAsync(match, new ArxDeleteOptions { Match = ArxMatch.Key("region", "sku") });

        Show($"{deleted} price deleted");

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * db.price_list.find({ batch: "M91" }, { region: 1, sku: 1 })
         * -- Expect: 2 documents: PT SKU-M912, ES SKU-M911.
         * ===========================================================
         */
    }

    /// <summary>2. RequireSingleRow with a field two documents share: ARX2003, nothing deleted.</summary>
    private static async Task Scenario2_RequireOneAsync(ArxMongoDbService service)
    {
        Step("2. Require exactly one");

        var match = new ArxEntity("price_list");
        match["batch"] = "M91";

        try
        {
            await service.DeleteAsync(match, new ArxDeleteOptions { Match = ArxMatch.Columns("batch"), RequireSingleRow = true });
        }
        catch (ArxException exception) when (exception.Code == ArxErrorCode.MultipleRecordsMatched)
        {
            ShowError(exception);
        }

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * db.price_list.countDocuments({ batch: "M91" })
         * -- Expect: 2.
         * ===========================================================
         */
    }

    /// <summary>3. Every price of the batch.</summary>
    private static async Task Scenario3_ByAnyFieldsAsync(ArxMongoDbService service)
    {
        Step("3. By any fields");

        var match = new ArxEntity("price_list");
        match["batch"] = "M91";

        int deleted = await service.DeleteAsync(match, new ArxDeleteOptions { Match = ArxMatch.Columns("batch") });

        Show($"{deleted} prices deleted");

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * db.price_list.countDocuments({ batch: "M91" })
         * -- 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 a compound key
      1 price deleted
  > 2. Require exactly one
      caught ArxException: ARX2003 MultipleRecordsMatched: Delete of 'price_list': the entity matched several documents by columns (batch), but RequireSingleRow needs exactly one. Nothing was deleted.
  > 3. By any fields
      2 prices deleted