Transforms are operations that modify document values during query processing. This document details all available transforms and their usage.
Capitalizes the first letter of a string.
{ name: { $capitalize: { as: 'displayName' } } }
Formats string using template literals.
{
user: {
$format: {
as: 'greeting',
format: 'Hello, ${name}!',
values: { title: 'Mr.' }
}
}
}
Joins array elements into string.
{ tags: { $join: { as: 'tagList', separator: ', ' } } }
Splits string into array.
{ csv: { $split: { as: 'values', separator: ',' } } }
Computes absolute value.
{ balance: { $abs: { as: 'absoluteBalance' } } }
Rounds number to nearest integer or up/down.
{ price: { $round: { as: 'roundedPrice' } } }
Restricts number to range.
{
score: {
$clamp: {
as: 'normalizedScore',
min: 0,
max: 100
}
}
}
Splits array into smaller arrays.
{ items: { $chunk: { as: 'pages', size: 10 } } }
Flattens nested array.
{ nested: { $flatten: { as: 'flat', depth: 1 } } }
Sorts array elements.
{
scores: {
$sort: {
as: 'sortedScores',
compare: (a, b) => b - a
}
}
}
Computes statistical measures.
{
values: {
$statistics: {
as: 'stats',
array: [1, 2, 3, 4, 5]
}
}
}
Calculates percentile value.
{
values: {
$percentile: {
as: 'p90',
array: [1, 2, 3, 4, 5],
p: 90
}
}
}
Formats date using specified pattern.
{
created: {
$dateFormat: {
as: 'formattedDate',
format: 'YYYY-MM-DD'
}
}
}
All transforms receive three arguments:
- The value to transform
- An options object containing:
as
: Output property name (defaults to source property name if not provided)- Any additional transform-specific options
- A context object containing:
transform
: The name of the transform being appliedproperty
: The source property nameobject
: The parent object containing the property
If the as
option is not provided, the transform will use the source property name for the output. This means:
// These are equivalent:
{ name: { $capitalize: { as: 'name' } } }
{ name: { $capitalize: {} } }
Example of a custom transform:
ChocolateMango.addTransform('$reverseString', (value, options, context) => {
// value: The value to transform
// options: { as: 'outputName', ...other options }
// context: { transform: '$reverseString', property: 'name', object: parentObj }
return typeof value === 'string' ?
value.split('').reverse().join('') :
undefined;
});
// Usage with explicit output property:
{
name: { $reverseString: { as: 'reversedName' } }
}
// Usage with implicit output property:
{
name: { $reverseString: {} } // Will store result in 'name'
}