Delete all documents in a collection

913 views
Skip to first unread message

Matt Johnson

unread,
Mar 8, 2012, 4:28:52 PM3/8/12
to ravendb
Just thought I would share this with the community in case it is
useful to others.

In my unit tests, I often need to reset the data by deleting an entire
collection of a particular type of document. Many samples and other
posts show this with the following:

Data.DocumentStore.DatabaseCommands.DeleteByIndex("Raven/
DocumentsByEntityName", new IndexQuery { Query = "Tag:MyEntities" });

However, it appears that Raven/DocumentsByEntityName is not created
unless you open the management UI. So I wrote a simple extension
method that will do the trick. It also deletes the system hilo
document for the entity to reset the count back to 1.

You can invoke with documentStore.WipeCollection<MyEntities>();

Enjoy!
-Matt


public static void WipeCollection<T>(this IDocumentStore
documentStore)
{
// delete all documents
using (var session = documentStore.OpenSession())
{
var docs = session.Query<T>()
.Customize(x => x.WaitForNonStaleResults());
foreach (var doc in docs)
session.Delete(doc);
session.SaveChanges();
}

// get the document prefix
var c = documentStore.Conventions;
var name = c.GetTypeTagName(typeof(T));
var prefix = c.TransformTypeTagNameToDocumentKeyPrefix(name);

// delete the hilo document for this type if it exists
var key = "Raven/Hilo/" + prefix;
var hilo = documentStore.DatabaseCommands.Get(key);
if (hilo != null)
documentStore.DatabaseCommands.Delete(key, null);
}

Justin A

unread,
Mar 9, 2012, 7:48:19 PM3/9/12
to rav...@googlegroups.com
Hi Matt,

just out of curiosity .. are you deleting entire collections so the -next- unit test is 'reset'? or is this for something that you do in the -same- unit test. eg. create collection. do some stuff .. delete collection. then do more stuff?

Itamar Syn-Hershko

unread,
Mar 10, 2012, 2:34:04 PM3/10/12
to rav...@googlegroups.com
You probably want to use the in-memory DB for unit tests, you usually don't need to do any deletes when testing

Matt Johnson

unread,
Mar 29, 2012, 12:17:33 PM3/29/12
to ravendb
I was deleting all data just once before running all unit tests, in
the test assembly initialization. But now, I am now using the in-
memory db so it's not neccessary.

-Matt

On Mar 10, 12:34 pm, Itamar Syn-Hershko <ita...@hibernatingrhinos.com>
wrote:
Reply all
Reply to author
Forward
0 new messages