Sinaesthetic
Sinaesthetic

Reputation: 12241

How can I "Add or Update" a document

So I know I can patch, I know I can store, and I know I can put, but what I'm clear on is how can I do an "upsert" type operation, where I want to add the object if it doesn't exist, or patch it if it does.

Is this possible in RavenDb 4.1+ ?

Right now, I'm kind of here but it feels wrong:

foreach (var flag in data)
{
    var exists = await _session.Advanced.ExistsAsync(flag.Id);
    if (!exists)
    {
        await _session.StoreAsync(flag);
    }
    else
    {
        await _store.Operations.ForDatabase("FeatureFlags").SendAsync(
            new PatchOperation(
                id: flag.Id,
                changeVector: null,
                patch: new PatchRequest
                {
                    Script = @"
                        this.Name = args.Name
                        this.Description = args.Description
                        ",
                    Values =
                    {
                        ["Name"] = flag.Name,
                        ["Description"] = flag.Description
                    }
                }));
    }
}

await _session.SaveChangesAsync();

Upvotes: 1

Views: 520

Answers (1)

Danielle
Danielle

Reputation: 3839

Use patchIfMissing with PatchCommandData or with Operations API

This provides the option to run a script if the document does not exist.
"Modify or create" style of operation.

  1. See https://ravendb.net/docs/article-page/4.2/Csharp/glossary/patch-command-data
  2. https://ravendb.net/docs/article-page/4.2/Csharp/client-api/operations/patching/single-document#non-typed-session-api
  3. Find more 'patch' info in:
    https://github.com/ravendb/book/blob/v4.0/Ch04/Ch04.md#patching-documents-and-concurrent-modifications

Upvotes: 3

Related Questions