[data-reveal]{opacity:1!important;transform:none!important}
Database

Selection

The Selection<T> class represents a set of documents and provides methods for bulk mutation operations. It extends Stream<T>, inheriting all transformation, filtering, and aggregation capabilities.

Class Definition

class Selection<T> extends Stream<T> {
  update(document: DeepPartial<T>): Query<number>;
  update<U>(document: (val: ValueProxy<T>) => U): Query<number>;
  replace(document: DeepPartial<T>): Query<number>;
  delete(): Query<number>;
}

Create a Selection

Selections are produced by table methods such as getAll() and between(), or by chaining stream operations like filter():

import { Schema } from "@antelopejs/interface-database";

const schema = Schema.get("myapp")!;
const users = schema.instance().table("users");

// Selection from getAll
const admins = users.getAll("admin", "role");

// Selection from between
const recentUsers = users.between("createdAt", new Date("2024-01-01"), new Date());

Update Documents

The update method modifies matching documents with the provided partial data. Fields not included in the update object remain unchanged. It returns the number of modified documents.

// Update with a partial object
const count = await users
  .getAll("inactive", "status")
  .update({ status: "active" });

console.log(`Activated ${count} users`);

// Update with a function for computed values
await users
  .getAll("active", "status")
  .update((user) => ({
    loginCount: user.key("loginCount").add(1),
  }));

Replace Documents

The replace method substitutes entire documents with the provided data. Unlike update, all fields not present in the replacement are removed.

const count = await users
  .getAll("user-123")
  .replace({
    _id: "user-123",
    name: "New Name",
    email: "[email protected]",
    role: "user",
  });

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

Delete Documents

The delete method removes all documents in the selection and returns the number of deleted documents.

const count = await users
  .getAll("inactive", "status")
  .delete();

console.log(`Deleted ${count} inactive users`);

Inherited Methods

Since Selection extends Stream, it inherits all stream operations:

  • Transformation: map(), pluck(), without()
  • Filtering: filter()
  • Aggregation: count(), sum(), avg(), min(), max()
  • Joining: join(), joinInner(), lookup()
  • Ordering: orderBy(), slice(), nth()
  • Grouping: group()
  • Deduplication: distinct()

See Stream for complete details on these methods.