MongoDB · CreateMultiple
Create many records in one call
Many documents in one call, all or nothing, with one id per entity in list order, in two scenarios: the call that stores them all, and the call that stores none because one of them fails.
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.
1 All stored
Three accounts in one call: the ids come back in the list's order.
Already in scope: service (ArxMongoDbService)
var accounts = new List<ArxEntity>();
foreach (var (name, number) in new[] { ("Alpine Ski House", "ACC-M101"), ("Blue Yonder Airlines", "ACC-M102"), ("Coho Winery", "ACC-M103") })
{
var account = new ArxEntity("account");
account["name"] = name;
account["account_number"] = number;
accounts.Add(account);
}
IReadOnlyList<ArxRecordId> ids = await service.CreateMultipleAsync(accounts);
Console.WriteLine($"created {ids.Count} accounts, the first {ids[0].AsString()}");Check it in the database
Run it in mongosh connected to the database, after the code has run.
db.account.find({ account_number: { $in: ["ACC-M101", "ACC-M102", "ACC-M103"] } })Expect: 3 documents.
2 One fails, none is stored
The second account repeats an account number (a unique index): none of the three is stored.
Already in scope: service (ArxMongoDbService)
var first = new ArxEntity("account");
first["name"] = "Fabrikam Inc.";
first["account_number"] = "ACC-M104";
var repeated = new ArxEntity("account");
repeated["name"] = "Fabrikam again";
repeated["account_number"] = "ACC-M104";
var third = new ArxEntity("account");
third["name"] = "Graphic Design Institute";
third["account_number"] = "ACC-M105";
try
{
await service.CreateMultipleAsync(new[] { first, repeated, third });
}
catch (ArxDatabaseException exception) when (exception.Code == ArxErrorCode.UniqueViolation)
{
Console.WriteLine(exception.Message);
}Check it in the database
Run it in mongosh connected to the database, after the code has run.
db.account.find({ account_number: { $in: ["ACC-M104", "ACC-M105"] } })Expect: no documents.
Good to know
CreateMultiple runs in a transaction, which MongoDB offers on a replica set (one node is enough) or a sharded cluster. On a standalone server it is refused rather than half done.
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
- .NET SDK: .NET SDK 10.0.100 or later 10.0.x (target
net10.0). - Create the project:
Terminal dotnet new console -n ArxSample -f net10.0 cd ArxSample - Install the packages:
Terminal dotnet add package ARX.SDK.MongoDb --version 1.0.0-rc.1 - Database: a MongoDB 7.0, a replica set (tested with 7.0.45, one node) database with the sample schema.
- Configuration: set
ARX_SAMPLES_MONGODBto its connection string. Nothing is hard-coded. - 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 replaceProgram.csand add the other file below, with the file names shown. - Run it:
Terminal dotnet run - Expected output: below.
The files
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.CreateMultiple.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_CreateManyRecords().RunAsync(dbContext);
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.CreateMultiple.Basics;
/// <summary>
/// Many documents in one call, all or nothing, with one id per entity in list order, in two scenarios: the call that
/// stores them all, and the call that stores none because one of them fails.
/// </summary>
/// <remarks>
/// CreateMultiple runs in a transaction, which MongoDB offers on a replica set (one node is enough) or a sharded
/// cluster. On a standalone server it is refused rather than half done.
/// </remarks>
public sealed class Basic1_CreateManyRecords : ISample
{
public string Name => "create-multiple-basics-1-create-many-records";
public string Title => "Create many records in one call";
public async Task RunAsync(SampleContext dbContext)
{
await Scenario1_AllStoredAsync(dbContext.Service);
await Scenario2_OneFailsAndNoneIsStoredAsync(dbContext.Service);
}
/// <summary>1. Three accounts in one call: the ids come back in the list's order.</summary>
private static async Task Scenario1_AllStoredAsync(ArxMongoDbService service)
{
Step("1. All stored");
var accounts = new List<ArxEntity>();
foreach (var (name, number) in new[] { ("Alpine Ski House", "ACC-M101"), ("Blue Yonder Airlines", "ACC-M102"), ("Coho Winery", "ACC-M103") })
{
var account = new ArxEntity("account");
account["name"] = name;
account["account_number"] = number;
accounts.Add(account);
}
IReadOnlyList<ArxRecordId> ids = await service.CreateMultipleAsync(accounts);
Show($"created {ids.Count} accounts, the first {ids[0].AsString()}");
/* ===========================================================
* [DIRECT QUERY CHECK]
* -----------------------------------------------------------
* db.account.find({ account_number: { $in: ["ACC-M101", "ACC-M102", "ACC-M103"] } })
* -- Expect: 3 documents.
* ===========================================================
*/
}
/// <summary>2. The second account repeats an account number (a unique index): none of the three is stored.</summary>
private static async Task Scenario2_OneFailsAndNoneIsStoredAsync(ArxMongoDbService service)
{
Step("2. One fails, none is stored");
var first = new ArxEntity("account");
first["name"] = "Fabrikam Inc.";
first["account_number"] = "ACC-M104";
var repeated = new ArxEntity("account");
repeated["name"] = "Fabrikam again";
repeated["account_number"] = "ACC-M104";
var third = new ArxEntity("account");
third["name"] = "Graphic Design Institute";
third["account_number"] = "ACC-M105";
try
{
await service.CreateMultipleAsync(new[] { first, repeated, third });
}
catch (ArxDatabaseException exception) when (exception.Code == ArxErrorCode.UniqueViolation)
{
ShowError(exception);
}
/* ===========================================================
* [DIRECT QUERY CHECK]
* -----------------------------------------------------------
* db.account.find({ account_number: { $in: ["ACC-M104", "ACC-M105"] } })
* -- Expect: no documents.
* ===========================================================
*/
}
}
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.
> 1. All stored
created 3 accounts, the first 6af533c9162ec0b1c7534aa3
> 2. One fails, none is stored
caught ArxDatabaseException: ARX3001 UniqueViolation: CreateMultiple on 'account': a record with the same value in unique index 'account_number_1' already exists.