MongoDB · UpdateMultiple
Update many records in one call
Many documents in one call, all or nothing, in two scenarios: a different value for each document, and a list with one id no document has, where none of them changes.
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:
var accounts = new List<ArxEntity>();
foreach (var number in new[] { "ACC-M921", "ACC-M922", "ACC-M923" })
{
var account = new ArxEntity("account");
account["name"] = "Many updates " + number;
account["account_number"] = number;
account["employee_count"] = 10;
accounts.Add(account);
}
var ids = await service.CreateMultipleAsync(accounts);1 A value per document
One entity per document, each with its own value: the call returns how many changed.
Already in scope: service (ArxMongoDbService), ids (IReadOnlyList<ArxRecordId>)
var changes = new List<ArxEntity>();
for (var i = 0; i < ids.Count; i++)
{
var change = new ArxEntity("account") { RecordId = ids[i] };
change["employee_count"] = 100 + i;
changes.Add(change);
}
int changed = await service.UpdateMultipleAsync(changes);
Console.WriteLine($"{changed} documents changed in one call");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-M921", "ACC-M922", "ACC-M923"] } }, { account_number: 1, employee_count: 1 }).sort({ account_number: 1 })Expect: 3 documents, employee_count 100, 101, 102.
2 All or nothing
The second id belongs to no document: RecordNotFound, and the first document keeps its value too.
Already in scope: service (ArxMongoDbService), existing (ArxRecordId)
var first = new ArxEntity("account") { RecordId = existing };
first["employee_count"] = 999;
var missing = new ArxEntity("account");
missing["account_id"] = "65a000000000000000000000";
missing["employee_count"] = 999;
try
{
await service.UpdateMultipleAsync(new[] { first, missing });
}
catch (ArxException exception) when (exception.Code == ArxErrorCode.RecordNotFound)
{
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: "ACC-M921" }, { employee_count: 1 })Expect: employee_count 100 (not 999).
Good to know
UpdateMultiple 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. Each entity writes only the fields it sets.
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.UpdateMultiple.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_UpdateManyRecords().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.UpdateMultiple.Basics;
/// <summary>
/// Many documents in one call, all or nothing, in two scenarios: a different value for each document, and a list with
/// one id no document has, where none of them changes.
/// </summary>
/// <remarks>
/// UpdateMultiple 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. Each entity writes only the fields it sets.
/// </remarks>
public sealed class Basic1_UpdateManyRecords : ISample
{
public string Name => "update-multiple-basics-1-update-many-records";
public string Title => "Update many records in one call";
public async Task RunAsync(SampleContext dbContext)
{
var accounts = new List<ArxEntity>();
foreach (var number in new[] { "ACC-M921", "ACC-M922", "ACC-M923" })
{
var account = new ArxEntity("account");
account["name"] = "Many updates " + number;
account["account_number"] = number;
account["employee_count"] = 10;
accounts.Add(account);
}
var ids = await dbContext.Service.CreateMultipleAsync(accounts);
await Scenario1_AValuePerDocumentAsync(dbContext.Service, ids);
await Scenario2_AllOrNothingAsync(dbContext.Service, ids[0]);
}
/// <summary>1. One entity per document, each with its own value: the call returns how many changed.</summary>
private static async Task Scenario1_AValuePerDocumentAsync(ArxMongoDbService service, IReadOnlyList<ArxRecordId> ids)
{
Step("1. A value per document");
var changes = new List<ArxEntity>();
for (var i = 0; i < ids.Count; i++)
{
var change = new ArxEntity("account") { RecordId = ids[i] };
change["employee_count"] = 100 + i;
changes.Add(change);
}
int changed = await service.UpdateMultipleAsync(changes);
Show($"{changed} documents changed in one call");
/* ===========================================================
* [DIRECT QUERY CHECK]
* -----------------------------------------------------------
* db.account.find({ account_number: { $in: ["ACC-M921", "ACC-M922", "ACC-M923"] } }, { account_number: 1, employee_count: 1 }).sort({ account_number: 1 })
* -- Expect: 3 documents, employee_count 100, 101, 102.
* ===========================================================
*/
}
/// <summary>2. The second id belongs to no document: RecordNotFound, and the first document keeps its value too.</summary>
private static async Task Scenario2_AllOrNothingAsync(ArxMongoDbService service, ArxRecordId existing)
{
Step("2. All or nothing");
var first = new ArxEntity("account") { RecordId = existing };
first["employee_count"] = 999;
var missing = new ArxEntity("account");
missing["account_id"] = "65a000000000000000000000";
missing["employee_count"] = 999;
try
{
await service.UpdateMultipleAsync(new[] { first, missing });
}
catch (ArxException exception) when (exception.Code == ArxErrorCode.RecordNotFound)
{
ShowError(exception);
}
/* ===========================================================
* [DIRECT QUERY CHECK]
* -----------------------------------------------------------
* db.account.find({ account_number: "ACC-M921" }, { employee_count: 1 })
* -- Expect: employee_count 100 (not 999).
* ===========================================================
*/
}
}
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. A value per document
3 documents changed in one call
> 2. All or nothing
caught ArxException: ARX2002 RecordNotFound: UpdateMultiple of 'account': 1 of 2 entities matched no document. Nothing was changed.