MongoDB · DeleteMultiple

Delete many records in one call

Many documents in one call, in two scenarios: by the ids Create returned, and by a list of entities found by the declared key (the account number).

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 ids = new List<ArxRecordId>();
foreach (var number in new[] { "ACC-M902", "ACC-M903", "ACC-M904", "ACC-M905" })
{
    var account = new ArxEntity("account");
    account["name"] = "To delete " + number;
    account["account_number"] = number;
    ids.Add(await service.CreateAsync(account));
}

1 By ids

Two ids in one call.

Already in scope: service (ArxMongoDbService), ids (IReadOnlyList<ArxRecordId>)

C#
int deleted = await service.DeleteMultipleAsync("account", ids);

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

Check it in the database

javascript

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

db.account.countDocuments({ account_number: { $in: ["ACC-M902", "ACC-M903"] } })

Expect: 0.

2 By the declared key

A list of account numbers, one of them unknown: the two found go.

Already in scope: service (ArxMongoDbService)

C#
var requests = new[] { "ACC-M904", "ACC-M905", "ACC-M999" }.Select(number =>
{
    var request = new ArxEntity("account");
    request["account_number"] = number;
    return request;
}).ToList();

int deleted = await service.DeleteMultipleAsync(requests, new ArxDeleteOptions { Match = ArxMatch.Key("account_number") });

Console.WriteLine($"{deleted} of {requests.Count} documents deleted");

Check it in the database

javascript

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

db.account.countDocuments({ account_number: { $in: ["ACC-M904", "ACC-M905"] } })

Expect: 0.

Good to know

By ids, ARX sends one deleteMany with $in. By entities, the deletes run in one transaction (a replica set or a sharded cluster). Either way the call returns how many documents went: an id or a key no document has isn't an error.

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.DeleteMultiple.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_DeleteManyRecords().RunAsync(dbContext);
Basic1_DeleteManyRecords.cs

The sample, as it is in the repository.

using ARX.SDK.MongoDb.Services;
using ARX.SDK.Services;

using static ArxSamples.MongoDb.SampleOutput;

namespace ArxSamples.MongoDb.Operations.DeleteMultiple.Basics;

/// <summary>
/// Many documents in one call, in two scenarios: by the ids Create returned, and by a list of entities found by the
/// declared key (the account number).
/// </summary>
/// <remarks>
/// By ids, ARX sends one <c>deleteMany</c> with <c>$in</c>. By entities, the deletes run in one transaction (a replica
/// set or a sharded cluster). Either way the call returns how many documents went: an id or a key no document has
/// isn't an error.
/// </remarks>
public sealed class Basic1_DeleteManyRecords : ISample
{
    public string Name => "delete-multiple-basics-1-delete-many-records";

    public string Title => "Delete many records in one call";

    public async Task RunAsync(SampleContext dbContext)
    {
        var ids = new List<ArxRecordId>();

        foreach (var number in new[] { "ACC-M902", "ACC-M903", "ACC-M904", "ACC-M905" })
        {
            var account = new ArxEntity("account");
            account["name"] = "To delete " + number;
            account["account_number"] = number;
            ids.Add(await dbContext.Service.CreateAsync(account));
        }

        await Scenario1_ByIdsAsync(dbContext.Service, ids.Take(2).ToList());

        await Scenario2_ByTheDeclaredKeyAsync(dbContext.Service);
    }

    /// <summary>1. Two ids in one call.</summary>
    private static async Task Scenario1_ByIdsAsync(ArxMongoDbService service, IReadOnlyList<ArxRecordId> ids)
    {
        Step("1. By ids");

        int deleted = await service.DeleteMultipleAsync("account", ids);

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

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * db.account.countDocuments({ account_number: { $in: ["ACC-M902", "ACC-M903"] } })
         * -- Expect: 0.
         * ===========================================================
         */
    }

    /// <summary>2. A list of account numbers, one of them unknown: the two found go.</summary>
    private static async Task Scenario2_ByTheDeclaredKeyAsync(ArxMongoDbService service)
    {
        Step("2. By the declared key");

        var requests = new[] { "ACC-M904", "ACC-M905", "ACC-M999" }.Select(number =>
        {
            var request = new ArxEntity("account");
            request["account_number"] = number;
            return request;
        }).ToList();

        int deleted = await service.DeleteMultipleAsync(requests, new ArxDeleteOptions { Match = ArxMatch.Key("account_number") });

        Show($"{deleted} of {requests.Count} documents deleted");

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * db.account.countDocuments({ account_number: { $in: ["ACC-M904", "ACC-M905"] } })
         * -- 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 ids
      2 documents deleted
  > 2. By the declared key
      2 of 3 documents deleted