Materialized Views
DianaDb allows you to create a view based on some predefined aggregation, and this view will automatically update if the data in the collections it uses changes.
This isn't sugar for aggregations like in other databases — it's a truly powerful feature.
Especially taking into account that DianaDb aggregations (that are base for materialized views) allow to make lookups (join) from other databases.
How a view is kept up to date depends on its stages. A view made only of $match, $project, $unwind, $replaceRoot and $lookup is updated per document: a write re-evaluates just the documents it touched. A view with $group, $sort, $skip or $limit, and any change in a $lookup target collection, triggers a full rebuild instead, throttled so rebuilds can't take over the server.
A view is complete when createView answers (since Server 4.8.35), and a view whose pipeline fails on the documents there are is refused instead of being created empty. $sum and $avg leave out a document in which the property has no value (since 4.8.31); before, one such document failed the aggregation, and a view over the collection stopped following it.
Let's see how we can use a materialized view of a collection with user transactions to quickly query a user's balance.
// Firstly create transaction model
const transactionModel = new Model({
database: 'test',
collection: 'transaction',
name: 'Transaction',
schema: {
user: {
type: Types.REFERENCE,
reference: 'user',
required: true,
triggerRemove: true
},
currency: {
type: Types.STRING,
required: true,
},
amount: {
type: Types.NUMBER,
default: 0,
precision: 0,
},
status: {
type: Types.STRING,
default: 'pending',
},
created: {
type: Types.TIME,
default() {
return new Date().toISOString();
},
},
updated: {
type: Types.TIME,
default() {
return new Date().toISOString();
},
},
},
});
await transactionModel.init();
// Then create materialized view
await transactionModel.createView('balance',
[
{
$group: {
_id: {
user: '$user',
currency: '$currency'
},
user: {
$first: '$user'
},
amount: {
$sum: ['$amount'],
},
currency: {
$first: '$currency',
},
},
},
]);
// Then use created view to retrieve user's balance:
const balances = await transactionModel.findByView('balance', { user: { $eq: someUser._id } }, { amount: -1 });
const balancesCount = await transactionModel.countByView('balance', { user: { $eq: someUser._id } });
createView method allows 2 arguments, all of them are required:
| Argument | Description |
|---|---|
name | Unique name for materialized view. A name already used by a collection or a view of the database is refused. Creating a view needs write access since 4.7.16 |
Transform Queries | An array of step-by-step transformation objects (pretty similar to MongoDB aggregation pipelines). |
removeView method allows 1 required arguments
| Argument | Description |
|---|---|
name | Unique name of the materialized view that should be removed |
findByView method allows 5 arguments, first one is required:
| Argument | Description |
|---|---|
name | Name of materialized view |
FindQuery | Special object where keys match view items dto and values are query operands. |
Sorting Query | Object for sorting results by schema keys. Values: 1 for ascending, -1 for descending. Supports multi-key sorting. |
Skip | Integer ≥ 0Positive integer. Skips a number of documents. |
Limit | Positive integer. Limits the number of documents returned. |
countByView method allows 2 arguments:
| Argument | Description |
|---|---|
name | Name of materialized view |
FindQuery | Special object where keys match view items dto and values are query operands. |