or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

administration.mdaql-queries.mddatabase-connection.mddocument-collections.mdgraph-operations.mdindex.mdquery-execution.mdtransactions.mdviews-search.md
tile.json

document-collections.mddocs/

Document Collections

Document storage and retrieval operations for working with JSON documents in ArangoDB collections, providing full CRUD operations with type safety and comprehensive options.

Capabilities

Collection Access and Management

Access and manage document collections within a database.

/**
 * Gets a reference to a document collection
 * @param collectionName - Name of the collection
 * @returns Document collection instance (also works as edge collection)
 */
collection<T = any, U = T>(collectionName: string): DocumentCollection<T, U> & EdgeCollection<T, U>;

/**
 * Creates a new document collection
 * @param collectionName - Name for the new collection
 * @param options - Collection creation options
 * @returns Promise resolving to DocumentCollection instance
 */
createCollection<T = any, U = T>(
  collectionName: string, 
  options?: CreateCollectionOptions
): Promise<DocumentCollection<T, U>>;

/**
 * Creates a new edge collection
 * @param collectionName - Name for the new edge collection  
 * @param options - Collection creation options
 * @returns Promise resolving to EdgeCollection instance
 */
createEdgeCollection<T = any, U = T>(
  collectionName: string,
  options?: CreateCollectionOptions  
): Promise<EdgeCollection<T, U>>;

/**
 * Lists all collections in the database
 * @param excludeSystem - Whether to exclude system collections
 * @returns Promise resolving to array of collection descriptions
 */
collections(excludeSystem?: boolean): Promise<Collection[]>;

Usage Examples:

import { Database } from "arangojs";

const db = new Database();

// Get reference to existing collection
const users = db.collection("users");
const posts = db.collection<BlogPost>("posts");

// Create new document collection
const products = await db.createCollection("products", {
  keyOptions: { type: "autoincrement" },
  schema: {
    level: "moderate",
    message: "Document does not match schema",
    rule: {
      type: "object",
      properties: {
        name: { type: "string" },
        price: { type: "number", minimum: 0 }
      },
      required: ["name", "price"]
    }
  }
});

// Create edge collection for relationships
const follows = await db.createEdgeCollection("follows");

// List all collections
const allCollections = await db.collections();
const userCollections = await db.collections(true); // exclude system

Collection Information and Status

Retrieve metadata and status information about collections.

/**
 * Checks if the collection exists
 * @returns Promise resolving to boolean indicating existence
 */
exists(): Promise<boolean>;

/**
 * Retrieves collection information and properties
 * @returns Promise resolving to collection description
 */
get(): Promise<CollectionDescription>;

/**
 * Creates the collection if it doesn't exist
 * @param options - Collection creation options
 * @returns Promise resolving to collection description
 */
create(options?: CreateCollectionOptions): Promise<CollectionDescription>;

/**
 * Drops (deletes) the collection
 * @param options - Drop options
 * @returns Promise resolving when collection is dropped
 */
drop(options?: DropCollectionOptions): Promise<void>;

/**
 * Gets or sets collection properties
 * @param properties - Properties to update (optional)
 * @returns Promise resolving to current/updated properties
 */
properties(properties?: CollectionPropertiesOptions): Promise<CollectionProperties>;

Usage Examples:

const collection = db.collection("users");

// Check if collection exists
if (!(await collection.exists())) {
  await collection.create({
    keyOptions: { type: "uuid" },
    waitForSync: true
  });
}

// Get collection information
const info = await collection.get();
console.log(`Collection ${info.name} has ${info.count} documents`);

// Update collection properties
await collection.properties({
  waitForSync: true,
  replicationFactor: 2
});

// Drop collection when no longer needed
await collection.drop();

Document Operations

Core CRUD operations for individual documents.

/**
 * Checks if a document exists
 * @param selector - Document key, ID, or object with _key/_id
 * @param options - Options for the existence check
 * @returns Promise resolving to boolean indicating existence
 */
documentExists(selector: DocumentSelector, options?: DocumentExistsOptions): Promise<boolean>;

/**
 * Retrieves a document by its selector
 * @param selector - Document key, ID, or object with _key/_id
 * @param options - Options for document retrieval
 * @returns Promise resolving to the document
 */
document(selector: DocumentSelector, options?: ReadDocumentOptions): Promise<Document<T>>;

/**
 * Saves a new document to the collection
 * @param data - Document data to save
 * @param options - Options for document insertion
 * @returns Promise resolving to operation result with metadata
 */
save(data: DocumentData<U>, options?: InsertDocumentOptions): Promise<DocumentOperationResult<T>>;

/**
 * Replaces an entire document
 * @param selector - Document selector (key, ID, or object)
 * @param data - New document data
 * @param options - Options for document replacement
 * @returns Promise resolving to operation result
 */
replace(
  selector: DocumentSelector,
  data: DocumentData<U>,
  options?: ReplaceDocumentOptions
): Promise<DocumentOperationResult<T>>;

/**
 * Updates part of a document
 * @param selector - Document selector
 * @param data - Partial document data to update
 * @param options - Options for document update
 * @returns Promise resolving to operation result
 */
update(
  selector: DocumentSelector,
  data: Patch<U>,
  options?: UpdateDocumentOptions
): Promise<DocumentOperationResult<T>>;

/**
 * Removes a document from the collection
 * @param selector - Document selector
 * @param options - Options for document removal
 * @returns Promise resolving to operation result
 */
remove(
  selector: DocumentSelector,
  options?: RemoveDocumentOptions
): Promise<DocumentOperationResult<T>>;

Usage Examples:

interface User {
  name: string;
  email: string;
  age: number;
  active: boolean;
}

const users = db.collection<User>("users");

// Save a new document
const newUser = await users.save({
  name: "Alice Johnson", 
  email: "alice@example.com",
  age: 28,
  active: true
}, { returnNew: true });

console.log("Created user:", newUser.new);

// Check if document exists
const exists = await users.documentExists(newUser._key);

// Retrieve document
const user = await users.document(newUser._key);
console.log("Retrieved user:", user.name);

// Update document
const updated = await users.update(newUser._key, {
  age: 29,
  lastLogin: new Date()
}, { returnOld: true, returnNew: true });

console.log("Old:", updated.old?.age);
console.log("New:", updated.new?.age);

// Replace entire document
const replaced = await users.replace(newUser._key, {
  name: "Alice Smith",
  email: "alice.smith@example.com", 
  age: 29,
  active: true,
  department: "Engineering"
});

// Remove document
const removed = await users.remove(newUser._key, { 
  returnOld: true 
});
console.log("Removed user:", removed.old?.name);

Bulk Operations

Efficient operations for handling multiple documents at once.

/**
 * Saves multiple documents in a single request
 * @param data - Array of document data objects
 * @param options - Options for bulk insertion
 * @returns Promise resolving to array of operation results
 */
saveAll(data: DocumentData<U>[], options?: InsertDocumentOptions): Promise<DocumentOperationResult<T>[]>;

/**
 * Replaces multiple documents
 * @param data - Array of documents with selectors and new data
 * @param options - Options for bulk replacement
 * @returns Promise resolving to array of operation results
 */
replaceAll(
  data: (DocumentData<U> & DocumentSelector)[],
  options?: ReplaceDocumentOptions
): Promise<DocumentOperationResult<T>[]>;

/**
 * Updates multiple documents
 * @param data - Array of partial updates with selectors
 * @param options - Options for bulk updates
 * @returns Promise resolving to array of operation results
 */
updateAll(
  data: (Patch<U> & DocumentSelector)[],
  options?: UpdateDocumentOptions
): Promise<DocumentOperationResult<T>[]>;

/**
 * Removes multiple documents
 * @param selectors - Array of document selectors
 * @param options - Options for bulk removal
 * @returns Promise resolving to array of operation results
 */
removeAll(
  selectors: DocumentSelector[],
  options?: RemoveDocumentOptions
): Promise<DocumentOperationResult<T>[]>;

Usage Examples:

// Bulk insert multiple users
const newUsers = await users.saveAll([
  { name: "Bob Wilson", email: "bob@example.com", age: 32, active: true },
  { name: "Carol Davis", email: "carol@example.com", age: 27, active: false },
  { name: "David Brown", email: "david@example.com", age: 35, active: true }
], { returnNew: true });

console.log(`Created ${newUsers.length} users`);

// Bulk update multiple documents
const updates = newUsers.map(result => ({
  _key: result._key,
  lastUpdated: new Date(),
  active: true
}));

const updatedResults = await users.updateAll(updates, { returnNew: true });

// Bulk remove by keys
const keysToRemove = ["user123", "user456", "user789"];
const removeResults = await users.removeAll(keysToRemove, { 
  returnOld: true 
});

console.log(`Removed ${removeResults.length} users`);

Advanced Operations

Advanced collection operations including bulk imports and truncation.

/**
 * Imports documents from various formats
 * @param data - Import data (JSON array, CSV, etc.)
 * @param options - Import configuration options
 * @returns Promise resolving to import result statistics
 */
import(data: any, options?: ImportOptions): Promise<ImportResult>;

/**
 * Removes all documents from the collection
 * @param options - Truncate options
 * @returns Promise resolving to truncate result
 */
truncate(options?: TruncateOptions): Promise<TruncateResult>;

/**
 * Counts documents in the collection
 * @returns Promise resolving to document count
 */
count(): Promise<number>;

/**
 * Gets random documents from the collection
 * @param options - Random sampling options
 * @returns Promise resolving to cursor with random documents
 */
any(options?: RandomOptions): Promise<Cursor<T>>;

Usage Examples:

// Import CSV data
const csvData = `name,email,age
John Doe,john@example.com,30
Jane Smith,jane@example.com,25`;

const importResult = await users.import(csvData, {
  type: "auto",
  separator: ",",
  quote: '"'
});

console.log(`Imported ${importResult.created} documents`);

// Count documents
const totalUsers = await users.count();
console.log(`Total users: ${totalUsers}`);

// Get random samples
const randomUsers = await users.any({ size: 5 });
const samples = await randomUsers.all();
console.log("Random samples:", samples);

// Truncate collection (remove all documents)
await users.truncate();
console.log("Collection truncated");

Types

interface DocumentCollection<T = any, U = T> extends ArangoCollection {
  readonly name: string;
  exists(): Promise<boolean>;
  get(): Promise<CollectionDescription>;
  document(selector: DocumentSelector, options?: ReadDocumentOptions): Promise<Document<T>>;
  save(data: DocumentData<U>, options?: InsertDocumentOptions): Promise<DocumentOperationResult<T>>;
  // ... other methods
}

interface ArangoCollection {
  readonly name: string;
  readonly isArangoCollection: true;
}

type DocumentSelector = string | DocumentMetadata;

interface DocumentMetadata {
  _key: string;
  _id: string;
  _rev: string;
}

type Document<T = any> = T & DocumentMetadata;
type DocumentData<T = any> = T & Partial<DocumentMetadata>;
type Patch<T> = { [K in keyof T]?: T[K] | Patch<T[K]> };

interface DocumentOperationResult<T = any> {
  _key: string;
  _id: string;
  _rev: string;
  _oldRev?: string;
  old?: T;
  new?: T;
}

interface CreateCollectionOptions {
  keyOptions?: {
    type?: KeyGenerator;
    allowUserKeys?: boolean;
    increment?: number;
    offset?: number;
  };
  waitForSync?: boolean;
  doCompact?: boolean;
  journalSize?: number;
  isSystem?: boolean;
  isVolatile?: boolean;
  numberOfShards?: number;
  shardKeys?: string[];
  replicationFactor?: number | "satellite";
  minReplicationFactor?: number;
  writeConcern?: number;
  shardingStrategy?: ShardingStrategy;
  distributeShardsLike?: string;
  smartJoinAttribute?: string;
  schema?: SchemaOptions;
  computedValues?: ComputedValueOptions[];
}

type KeyGenerator = "traditional" | "autoincrement" | "uuid" | "padded";
type ShardingStrategy = "community-compat" | "enterprise-compat" | "enterprise-smart-edge-compat" | "hash" | "enterprise-hash-smart-edge";

interface InsertDocumentOptions {
  waitForSync?: boolean;
  returnNew?: boolean;
  returnOld?: boolean;
  silent?: boolean;
  overwrite?: boolean;
  overwriteMode?: "ignore" | "replace" | "update" | "conflict";
  keepNull?: boolean;
  mergeObjects?: boolean;
}

interface UpdateDocumentOptions extends InsertDocumentOptions {
  ignoreRevs?: boolean;
}

interface ReplaceDocumentOptions extends InsertDocumentOptions {
  ignoreRevs?: boolean;
}

interface RemoveDocumentOptions {
  waitForSync?: boolean;
  returnOld?: boolean;
  silent?: boolean;
  ignoreRevs?: boolean;
}