# CreateMultiple with ARX.SDK on MongoDB

## What a CreateMultiple does

| Rule | On MongoDB |
|---|---|
| Many documents | CreateMultiple is all or nothing, in a transaction (a replica set or sharded cluster; ARX8001 on a standalone server) |

## The samples

Every CreateMultiple sample, in reading order. Each scenario shows the code (verified against MongoDB) and the mongosh query that checks what it did. `service` is the application's `ArxMongoDbService`; values marked "In scope" come from earlier in the sample. What the samples' code refers to beyond the packages (SampleCatalog.cs, `dbContext`) is in the sample application file, arx-mongodb-sample-application.md.

### Create many records in one call

Basics 1 of CreateMultiple.

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.

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.

Usings:

```csharp
using ARX.SDK;
using ARX.SDK.MongoDb.Services;
using ARX.SDK.Services;
```

#### 1. All stored

Three accounts in one call: the ids come back in the list's order.

In scope: `service` (ArxMongoDbService).

```csharp
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:

```sql
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.

In scope: `service` (ArxMongoDbService).

```csharp
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:

```sql
db.account.find({ account_number: { $in: ["ACC-M104", "ACC-M105"] } })
```

Expect: no documents.

