MongoDB · Delete

Delete one record by id

Delete by id, in two scenarios: one document, and one that is already gone (not an error).

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"] = "To delete ACC-M901";
account["account_number"] = "ACC-M901";
var id = await service.CreateAsync(account);

1 One document

Delete the account by the id Create returned.

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

C#
bool deleted = await service.DeleteAsync("account", id);

Console.WriteLine($"deleted: {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: "ACC-M901" })

Expect: 0.

2 Already gone

The same id again: nothing to delete, false, no error.

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

C#
bool deleted = await service.DeleteAsync("account", id);

Console.WriteLine($"deleted: {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: "ACC-M901" })

Expect: 0.

Good to know

DeleteAsync(collection, id) returns whether a document went. Many ids in one call are DeleteMultiple's.

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

/// <summary>
/// Delete by id, in two scenarios: one document, and one that is already gone (not an error).
/// </summary>
/// <remarks>
/// <c>DeleteAsync(collection, id)</c> returns whether a document went. Many ids in one call are DeleteMultiple's.
/// </remarks>
public sealed class Basic1_DeleteOneRecord : ISample
{
    public string Name => "delete-basics-1-delete-one-record";

    public string Title => "Delete one record by id";

    public async Task RunAsync(SampleContext dbContext)
    {
        var account = new ArxEntity("account");
        account["name"] = "To delete ACC-M901";
        account["account_number"] = "ACC-M901";
        var id = await dbContext.Service.CreateAsync(account);

        await Scenario1_OneDocumentAsync(dbContext.Service, id);

        await Scenario2_AlreadyGoneAsync(dbContext.Service, id);
    }

    /// <summary>1. Delete the account by the id Create returned.</summary>
    private static async Task Scenario1_OneDocumentAsync(ArxMongoDbService service, ArxRecordId id)
    {
        Step("1. One document");

        bool deleted = await service.DeleteAsync("account", id);

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

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * db.account.countDocuments({ account_number: "ACC-M901" })
         * -- Expect: 0.
         * ===========================================================
         */
    }

    /// <summary>2. The same id again: nothing to delete, false, no error.</summary>
    private static async Task Scenario2_AlreadyGoneAsync(ArxMongoDbService service, ArxRecordId id)
    {
        Step("2. Already gone");

        bool deleted = await service.DeleteAsync("account", id);

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

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * db.account.countDocuments({ account_number: "ACC-M901" })
         * -- 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. One document
      deleted: True
  > 2. Already gone
      deleted: False