Search code examples
node.jsravendbdocument-database

Delete multiple documents of a particular collection matching a criteria in RavenDB


I am trying to delete multiple documents of a particular collection meeting certain criteria. Ideally after deleting these documents I need to add new documents. Even though the new documents are added successfully to the collections, when it comes to deletion only one document is deleted. Any help in the right direction is appreciated.

I have tried different combinations of async and await, but didn't work. Just to let you know, I am using the same session for both addition and deletion calls. Below is the method for deleting multiple documents accepting 'session' as an argument.

export async function deleteDocs(session: IDocumentSession, docs: IDoc[]) {
  docs.forEach(doc => {
    session.delete<Doc>(doc);
  });
 await session.saveChanges();
}

I should be able to delete all documents matching the criteria, and not just one.


Solution

  • DeleteByQueryOperation gives you the ability to delete a large number of documents with a single query

    For .Net Client
    See: https://ravendb.net/docs/article-page/4.1/Csharp/client-api/operations/delete-by-query

    For example: To remove all documents from the server where Name == Bob using Person/ByName index use:

    var operation = store
        .Operations
        .Send(new DeleteByQueryOperation<Person>("Person/ByName", x => x.Name == "Bob"));
    

    For Node Client:
    (example taken from tests)

      it("can delete by query", async () => {
            {
                const session = store.openSession();
                const user1 = Object.assign(new User(), { age: 5 });
                const user2 = Object.assign(new User(), { age: 10 });
    
                await session.store(user1);
                await session.store(user2);
                await session.saveChanges();
            }
    
            const indexQuery = new IndexQuery();
            indexQuery.query = "from users where age == 5";
            const operation = new DeleteByQueryOperation(indexQuery);
            const asyncOp = await store.operations.send(operation);
    
            await asyncOp.waitForCompletion();
    
            {
                const session = store.openSession();
                const count = await session.query(User).count();
                assert.strictEqual(count, 1);
            }
        });