or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced-querying.mdcollection-operations.mddatabase-management.mddynamic-views.mdindex.mdpersistence-adapters.md

dynamic-views.mddocs/

0

# Dynamic Views

1

2

Live, automatically updated views of collection data with persistent filtering and sorting. Dynamic views maintain their state and automatically update when the underlying collection changes.

3

4

## Capabilities

5

6

### Dynamic View Constructor

7

8

Creates a new dynamic view attached to a collection with automatic updates.

9

10

```javascript { .api }

11

/**

12

* Creates a new dynamic view

13

* @param collection - Source collection

14

* @param name - View name

15

* @param options - View configuration options

16

*/

17

constructor DynamicView(collection: Collection, name: string, options?: DynamicViewOptions);

18

19

interface DynamicViewOptions {

20

/** Persist filter pipeline */

21

persistent?: boolean;

22

/** Sort criteria array */

23

sortPriority?: string;

24

/** Minimum rebuild interval */

25

minRebuildInterval?: number;

26

}

27

```

28

29

**Usage Examples:**

30

31

```javascript

32

const users = db.getCollection('users');

33

34

// Create basic dynamic view

35

const activeUsers = users.addDynamicView('activeUsers');

36

37

// Create with options

38

const recentHires = users.addDynamicView('recentHires', {

39

persistent: true,

40

minRebuildInterval: 1000

41

});

42

```

43

44

### Filtering Operations

45

46

Apply persistent filters that automatically update when collection data changes.

47

48

```javascript { .api }

49

/**

50

* Apply a find filter to the view

51

* @param query - MongoDB-style query object

52

* @param uid - Optional unique identifier for the filter

53

* @returns DynamicView for chaining

54

*/

55

applyFind(query: object, uid?: string): DynamicView;

56

57

/**

58

* Apply a where filter using custom function

59

* @param fun - Filter function returning boolean

60

* @param uid - Optional unique identifier for the filter

61

* @returns DynamicView for chaining

62

*/

63

applyWhere(fun: (obj: object) => boolean, uid?: string): DynamicView;

64

65

/**

66

* Remove all filters from the view

67

* @param options - Remove options

68

* @returns DynamicView for chaining

69

*/

70

removeFilters(options?: object): DynamicView;

71

72

/**

73

* Remove specific filter by unique identifier

74

* @param uid - Filter unique identifier

75

* @returns DynamicView for chaining

76

*/

77

removeFilter(uid: string): DynamicView;

78

```

79

80

**Usage Examples:**

81

82

```javascript

83

// Apply find filter

84

const activeUsers = users.addDynamicView('activeUsers')

85

.applyFind({ active: true });

86

87

// Apply multiple filters with IDs

88

const engineeringView = users.addDynamicView('engineering')

89

.applyFind({ department: 'Engineering' }, 'dept-filter')

90

.applyFind({ level: { $in: ['Senior', 'Lead'] } }, 'level-filter');

91

92

// Apply custom where filter

93

const recentLoginView = users.addDynamicView('recentLogin')

94

.applyWhere(obj => {

95

const lastLogin = new Date(obj.lastLogin);

96

const weekAgo = new Date();

97

weekAgo.setDate(weekAgo.getDate() - 7);

98

return lastLogin > weekAgo;

99

}, 'recent-login-filter');

100

101

// Remove specific filter

102

engineeringView.removeFilter('level-filter');

103

104

// Remove all filters

105

engineeringView.removeFilters();

106

```

107

108

### Sorting Operations

109

110

Apply persistent sorting that is maintained as data changes.

111

112

```javascript { .api }

113

/**

114

* Apply custom sort function to the view

115

* @param comparefun - Function returning -1, 0, or 1 for comparison

116

* @returns DynamicView for chaining

117

*/

118

applySort(comparefun: (a: object, b: object) => number): DynamicView;

119

120

/**

121

* Apply simple sort by property name

122

* @param propname - Property name to sort by

123

* @param options - Sort options (desc: boolean)

124

* @returns DynamicView for chaining

125

*/

126

applySimpleSort(propname: string, options?: { desc?: boolean }): DynamicView;

127

128

/**

129

* Apply compound sort criteria

130

* @param criteria - Array of [property, isDescending] pairs

131

* @returns DynamicView for chaining

132

*/

133

applySortCriteria(criteria: [string, boolean][]): DynamicView;

134

135

/**

136

* Get current sort configuration

137

* @returns Current sort criteria

138

*/

139

getSort(): any;

140

```

141

142

**Usage Examples:**

143

144

```javascript

145

// Simple sort

146

const usersByName = users.addDynamicView('usersByName')

147

.applyFind({ active: true })

148

.applySimpleSort('name');

149

150

// Descending sort

151

const usersByAge = users.addDynamicView('usersByAge')

152

.applyFind({ active: true })

153

.applySimpleSort('age', { desc: true });

154

155

// Compound sort

156

const usersByDeptAndName = users.addDynamicView('usersByDeptAndName')

157

.applyFind({ active: true })

158

.applySortCriteria([

159

['department', false], // ascending

160

['name', false] // ascending

161

]);

162

163

// Custom sort

164

const usersByNameLength = users.addDynamicView('usersByNameLength')

165

.applySort((a, b) => a.name.length - b.name.length);

166

```

167

168

### Data Access Operations

169

170

Retrieve data from the dynamic view or create resultsets for further operations.

171

172

```javascript { .api }

173

/**

174

* Get data from the dynamic view

175

* @param options - Data retrieval options

176

* @returns Array of documents in the view

177

*/

178

data(options?: { removeMeta?: boolean, forceClones?: boolean }): object[];

179

180

/**

181

* Get count of documents in the view

182

* @returns Number of documents

183

*/

184

count(): number;

185

186

/**

187

* Create a branched resultset from the view for additional operations

188

* @param transform - Transform name to apply

189

* @param parameters - Transform parameters

190

* @returns Resultset for further chaining

191

*/

192

branchResultset(transform?: string, parameters?: object): Resultset;

193

```

194

195

**Usage Examples:**

196

197

```javascript

198

// Get all data from view

199

const activeUserData = activeUsers.data();

200

201

// Get data without metadata

202

const cleanData = activeUsers.data({ removeMeta: true });

203

204

// Get count

205

const activeCount = activeUsers.count();

206

207

// Branch for additional operations

208

const topActiveUsers = activeUsers.branchResultset()

209

.simplesort('lastLogin', { desc: true })

210

.limit(10)

211

.data();

212

```

213

214

### View Management Operations

215

216

Control view behavior and lifecycle.

217

218

```javascript { .api }

219

/**

220

* Force rematerialization of the view

221

* @param options - Rematerialize options

222

* @returns DynamicView for chaining

223

*/

224

rematerialize(options?: { removeWhereFilters?: boolean }): DynamicView;

225

226

/**

227

* Serialize dynamic view to JSON

228

* @returns JSON representation of the view

229

*/

230

toJSON(): string;

231

232

/**

233

* Re-apply all filters to rebuild the view

234

*/

235

reapplyFilters(): void;

236

237

/**

238

* Apply generic filter to the view

239

* @param filter - Filter object with type and parameters

240

* @returns DynamicView for chaining

241

*/

242

applyFilter(filter: object): DynamicView;

243

244

/**

245

* Find index of filter with specific unique identifier

246

* @param uid - Filter unique identifier

247

* @returns Index of filter or -1 if not found

248

*/

249

_indexOfFilterWithId(uid: string): number;

250

251

/**

252

* Add filter to the view's filter pipeline

253

* @param filter - Filter object to add

254

*/

255

_addFilter(filter: object): void;

256

257

/**

258

* Queue rebuild event for the view

259

*/

260

queueRebuildEvent(): void;

261

262

/**

263

* Queue sort phase for the view

264

*/

265

queueSortPhase(): void;

266

267

/**

268

* Perform sort phase with options

269

* @param options - Sort phase options

270

*/

271

performSortPhase(options?: object): void;

272

273

/**

274

* Evaluate document for inclusion in view

275

* @param objIndex - Document index

276

* @param isNew - Whether document is new

277

*/

278

evaluateDocument(objIndex: number, isNew?: boolean): void;

279

280

/**

281

* Remove document from view by index

282

* @param objIndex - Document index to remove

283

*/

284

removeDocument(objIndex: number): void;

285

```

286

287

**Usage Examples:**

288

289

```javascript

290

// Force rebuild of view

291

activeUsers.rematerialize();

292

293

// Serialize view configuration

294

const viewConfig = activeUsers.toJSON();

295

296

// Rebuild view filters

297

activeUsers.reapplyFilters();

298

```

299

300

### Transaction Support

301

302

Dynamic views support transactions for consistent state management.

303

304

```javascript { .api }

305

/**

306

* Start transaction on the view

307

* @returns DynamicView for chaining

308

*/

309

startTransaction(): DynamicView;

310

311

/**

312

* Commit current transaction

313

* @returns DynamicView for chaining

314

*/

315

commit(): DynamicView;

316

317

/**

318

* Rollback current transaction

319

* @returns DynamicView for chaining

320

*/

321

rollback(): DynamicView;

322

```

323

324

**Usage Examples:**

325

326

```javascript

327

// Use transactions for consistent updates

328

const managersView = users.addDynamicView('managers');

329

330

managersView.startTransaction()

331

.applyFind({ role: 'manager' })

332

.applySimpleSort('experience', { desc: true });

333

334

// Later decide to commit or rollback

335

if (validationPassed) {

336

managersView.commit();

337

} else {

338

managersView.rollback();

339

}

340

```

341

342

### Aggregation Operations

343

344

Perform aggregation operations on dynamic view data.

345

346

```javascript { .api }

347

/**

348

* Perform map-reduce operation on view data

349

* @param mapFunction - Map function to apply to each document

350

* @param reduceFunction - Reduce function to combine results

351

* @returns Reduced result

352

*/

353

mapReduce(mapFunction: (obj: object) => any, reduceFunction: (array: any[]) => any): any;

354

```

355

356

**Usage Examples:**

357

358

```javascript

359

// Calculate department statistics from active users view

360

const deptStats = activeUsers.mapReduce(

361

obj => ({ [obj.department]: 1 }),

362

results => {

363

const counts = {};

364

results.forEach(result => {

365

Object.keys(result).forEach(dept => {

366

counts[dept] = (counts[dept] || 0) + result[dept];

367

});

368

});

369

return counts;

370

}

371

);

372

```

373

374

## Advanced Usage Patterns

375

376

### Chained View Creation

377

378

Create complex views with multiple filters and sorting:

379

380

```javascript

381

const seniorEngineers = users.addDynamicView('seniorEngineers')

382

.applyFind({ department: 'Engineering' })

383

.applyFind({ level: { $in: ['Senior', 'Lead', 'Principal'] } })

384

.applyFind({ active: true })

385

.applySimpleSort('experience', { desc: true });

386

387

// View automatically updates when underlying data changes

388

users.insert({

389

name: 'Alice',

390

department: 'Engineering',

391

level: 'Senior',

392

active: true,

393

experience: 8

394

});

395

396

// Alice will automatically appear in seniorEngineers view

397

console.log(seniorEngineers.count()); // Increased by 1

398

```

399

400

### Performance Optimization

401

402

Use views for frequently accessed data subsets:

403

404

```javascript

405

// Create views for common queries

406

const activeCustomers = customers.addDynamicView('active')

407

.applyFind({ status: 'active' })

408

.applySimpleSort('lastPurchase', { desc: true });

409

410

const vipCustomers = customers.addDynamicView('vip')

411

.applyFind({ tier: 'VIP', status: 'active' })

412

.applySimpleSort('totalSpent', { desc: true });

413

414

// These views stay current automatically

415

// No need to re-query when data changes

416

```

417

418

### Real-time Dashboards

419

420

Use dynamic views for live dashboard data:

421

422

```javascript

423

const todaysSales = orders.addDynamicView('todaysSales')

424

.applyWhere(obj => {

425

const today = new Date().toDateString();

426

const orderDate = new Date(obj.createdAt).toDateString();

427

return orderDate === today;

428

})

429

.applySimpleSort('amount', { desc: true });

430

431

// Dashboard always shows current day's sales

432

setInterval(() => {

433

const totalSales = todaysSales.data()

434

.reduce((sum, order) => sum + order.amount, 0);

435

updateDashboard('todaysSales', totalSales);

436

}, 1000);

437

```

438

439

### Filter Management

440

441

Advanced filter pipeline management for dynamic views.

442

443

**Usage Examples:**

444

445

```javascript

446

// Apply generic filter

447

const view = users.addDynamicView('customView');

448

view.applyFilter({

449

type: 'find',

450

val: { active: true },

451

uid: 'active-filter'

452

});

453

454

// Check filter index

455

const filterIndex = view._indexOfFilterWithId('active-filter');

456

if (filterIndex !== -1) {

457

console.log('Filter found at index:', filterIndex);

458

}

459

460

// Manually queue operations

461

view.queueRebuildEvent();

462

view.queueSortPhase();

463

```

464

465

### Internal View Operations

466

467

Low-level methods for view management and optimization.

468

469

**Usage Examples:**

470

471

```javascript

472

// These methods are primarily for internal use

473

// Most applications should use the higher-level methods instead

474

475

// Manual sort phase execution

476

view.performSortPhase({ forceSort: true });

477

478

// Document evaluation (called automatically)

479

view.evaluateDocument(0, true); // Evaluate first document as new

480

view.removeDocument(5); // Remove document at index 5

481

```

482

483

## Properties

484

485

```javascript { .api }

486

interface DynamicView {

487

/** Reference to source collection */

488

collection: Collection;

489

/** View name */

490

name: string;

491

/** View options */

492

options: DynamicViewOptions;

493

/** Filter pipeline array */

494

filterPipeline: object[];

495

/** Sort function */

496

sortFunction: Function;

497

/** Sort criteria */

498

sortCriteria: [string, boolean][];

499

/** Internal resultset */

500

resultset: Resultset;

501

/** Result data array */

502

resultdata: object[];

503

/** Results dirty flag */

504

resultsdirty: boolean;

505

/** Sort dirty flag */

506

sortDirty: boolean;

507

/** Rebuild pending flag */

508

rebuildPending: boolean;

509

}

510

```