MongoDB · Retrieve

Read one record

Read one document, in three scenarios: by its id with every field, with chosen fields, and by a key; an id no document has reads null.

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"] = "Consolidated Messenger";
account["account_number"] = "ACC-M951";
account["employee_count"] = 75;
var id = await service.CreateAsync(account);

1 By id

By the id Create returned: every field.

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

C#
ArxEntity? account = await service.RetrieveAsync("account", id);

Console.WriteLine($"{account?["name"]}, {account?["employee_count"]} employees, id {account?["account_id"]}");

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-M951" })

Expect: 1 document, Consolidated Messenger, employee_count 75.

2 Chosen fields

Only the fields you name (the id always comes too).

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

C#
ArxEntity? account = await service.RetrieveAsync("account", id, new ArxColumnSet("name"));

Console.WriteLine($"fields read: {string.Join(", ", account!.Attributes.Keys)}");

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-M951" }, { name: 1 })

Expect: 1 document, _id and name.

3 By a key

By the account number (a declared key), and a number no account has: null.

Already in scope: service (ArxMongoDbService)

C#
var match = new ArxEntity("account");
match["account_number"] = "ACC-M951";
ArxEntity? found = await service.RetrieveAsync(match, new ArxRetrieveOptions { Match = ArxMatch.Key("account_number") });

match["account_number"] = "ACC-M959";
ArxEntity? missing = await service.RetrieveAsync(match, new ArxRetrieveOptions { Match = ArxMatch.Key("account_number") });

Console.WriteLine($"ACC-M951: {found?["name"]}; ACC-M959: {(missing == null ? "null" : "found")}");

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-M959" })

Expect: 0.

Good to know

The id comes back under the declared column's name (account_id) and as RecordId.

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.Retrieve.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_RetrieveOneRecord().RunAsync(dbContext);
Basic1_RetrieveOneRecord.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.Retrieve.Basics;

/// <summary>
/// Read one document, in three scenarios: by its id with every field, with chosen fields, and by a key; an id no
/// document has reads null.
/// </summary>
/// <remarks>The id comes back under the declared column's name (<c>account_id</c>) and as <see cref="ArxEntity.RecordId"/>.</remarks>
public sealed class Basic1_RetrieveOneRecord : ISample
{
    public string Name => "retrieve-basics-1-retrieve-one-record";

    public string Title => "Read one record";

    public async Task RunAsync(SampleContext dbContext)
    {
        var account = new ArxEntity("account");
        account["name"] = "Consolidated Messenger";
        account["account_number"] = "ACC-M951";
        account["employee_count"] = 75;
        var id = await dbContext.Service.CreateAsync(account);

        await Scenario1_ByIdAsync(dbContext.Service, id);

        await Scenario2_ChosenFieldsAsync(dbContext.Service, id);

        await Scenario3_ByAKeyAsync(dbContext.Service);
    }

    /// <summary>1. By the id Create returned: every field.</summary>
    private static async Task Scenario1_ByIdAsync(ArxMongoDbService service, ArxRecordId id)
    {
        Step("1. By id");

        ArxEntity? account = await service.RetrieveAsync("account", id);

        Show($"{account?["name"]}, {account?["employee_count"]} employees, id {account?["account_id"]}");

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * db.account.find({ account_number: "ACC-M951" })
         * -- Expect: 1 document, Consolidated Messenger, employee_count 75.
         * ===========================================================
         */
    }

    /// <summary>2. Only the fields you name (the id always comes too).</summary>
    private static async Task Scenario2_ChosenFieldsAsync(ArxMongoDbService service, ArxRecordId id)
    {
        Step("2. Chosen fields");

        ArxEntity? account = await service.RetrieveAsync("account", id, new ArxColumnSet("name"));

        Show($"fields read: {string.Join(", ", account!.Attributes.Keys)}");

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * db.account.find({ account_number: "ACC-M951" }, { name: 1 })
         * -- Expect: 1 document, _id and name.
         * ===========================================================
         */
    }

    /// <summary>3. By the account number (a declared key), and a number no account has: null.</summary>
    private static async Task Scenario3_ByAKeyAsync(ArxMongoDbService service)
    {
        Step("3. By a key");

        var match = new ArxEntity("account");
        match["account_number"] = "ACC-M951";
        ArxEntity? found = await service.RetrieveAsync(match, new ArxRetrieveOptions { Match = ArxMatch.Key("account_number") });

        match["account_number"] = "ACC-M959";
        ArxEntity? missing = await service.RetrieveAsync(match, new ArxRetrieveOptions { Match = ArxMatch.Key("account_number") });

        Show($"ACC-M951: {found?["name"]}; ACC-M959: {(missing == null ? "null" : "found")}");

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * db.account.countDocuments({ account_number: "ACC-M959" })
         * -- 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 id
      Consolidated Messenger, 75 employees, id 6af534034d10bda79422b8d8
  > 2. Chosen fields
      fields read: account_id, name
  > 3. By a key
      ACC-M951: Consolidated Messenger; ACC-M959: null