Removing Documents from a Collection with SODA for In-Database JavaScript

Removing documents from a collection is similar to replacing. The first step is to perform a lookup operation, usually based on the document's key or by using a search expression in SodaOperation.filter(). The call to SodaOperation.remove() is a terminal operation, in other words the last operation in the chain.

Example 8-16 Removing a Document from a Collection Using a Document Key

This example removes the document whose document key is "100".

export function removeByKey(searchKey){
  
  // open MyCollection
  const col = soda.openCollection("MyCollection");
  if(col === null){
    throw new Error("'MyCollection' does not exist");
  }

  // perform a lookup of the document about to be removed
  // and ultimately remove it
  const result = col
                 .find()
                 .key(searchKey)
                 .remove();
  if(result.count === 0){
    throw new Error(
      `failed to delete a document with key ${searchKey}`
    );
  }
}

Example 8-17 Removing JSON Documents from a Collection Using a Filter

This example uses a filter to remove the JSON documents whose department_id is 70. It then prints the number of documents removed.

export function removeByFilter(){

  // open the collection
  const col = soda.openCollection("MyCollection");
  if(col === null){
    throw new Error("'MyCollection' does not exist");
  }

  // perform a lookup based on a filter expression and remove
  // the documents matching the filter
  const result = col
                 .find()
                 .filter({"_id": 100})
                 .remove();

  console.log(`${result.count} documents deleted`);
}