How to move all documents from one RavenDB database to another?

Viewed 56

I initially was developing with separate databases - one for data, and another for configuration, but my queries are now such that I need to "join" the data from both databases. How can I merge these 2 databases as part of a migration process, using the C# API?

1 Answers

This can be done using the Raven.Client.Documents.Smuggler.DataSmuggler class:

using System.Threading.Tasks;
using Raven.Client.Documents;
using Raven.Client.ServerWide.Operations;

public class RavenDBMerger
{
  readonly IDocumentStore _store;

  public RavenDBMerger(IDocumentStore store)
  {
    _store = store;
  }

  public async Task MergeDatabases()
  {
    string sourceDbName = "source-database";

    var sourceDb = _store.Maintenance.Server.Send(new GetDatabaseRecordOperation(sourceDbName));

    if (sourceDb != null)
    {
      var smugglerFrom = _store.Smuggler.ForDatabase(sourceDbName);

      var smugglerTo = _store.Smuggler.ForDatabase("target-database");

      await smugglerFrom.ExportAsync(new Raven.Client.Documents.Smuggler.DatabaseSmugglerExportOptions(), smugglerTo);

      _store.Maintenance.Server.Send(new DeleteDatabasesOperation(sourceDbName, hardDelete: true));
    }
  }
}
Related