Expression function reference
Quoted DSL strings are literals: expr('"$price"') and expr('LITERAL("$price")') return the text $price; unquoted expr('$price') references the field. LITERAL preserves literal objects and arrays without interpreting their contents as DSL.
For $match, place an expression at the stage root ({ $match: expr('price > 10') }) or inside native $expr. A DSL marker used as a field-query value throws INVALID_EXPRESSION; native predicates, BSON/Date/RegExp values and $literal data remain native. Quoted strings use backslash parity when locating delimiters; escaping does not create an extra expression scope.
Nested facet/lookup/unionWith pipelines and merge whenMatched pipelines retain their stage context. Numeric arguments to SUBSTR/SUBSTR_CP/SLICE/ARRAY_ELEM_AT accept expressions without integer truncation. MAP/FILTER variables resolve lexically, including scalar variables, nesting and quoted literals; LET bindings use balanced separators and still require explicit $$name references. SWITCH preserves an explicit null/false/0/empty-string default; omitting a default keeps native MongoDB failure behavior. Scientific notation such as price * 1e-3 is supported; malformed numeric expressions fail with INVALID_EXPRESSION.
DSL lambda names and explicit MongoDB $$ variables have separate scopes. MAP/FILTER bind their named variable; REDUCE exposes native $$value/$$this only inside its body, while input and initial value use the outer scope. LET initializers use the outer scope and its body uses the declared explicit variables. Native JSON $map, $filter, $reduce and $let follow these lexical boundaries. Quoted text and $literal payloads remain unchanged.
For example, REDUCE([10],0,(acc,item)=>SUM(MAP([1,2],value,$$value))) evaluates to 3. In MAP([10],value,REDUCE([1,2],0,(acc,item)=>$$value + $$this)), the explicit references belong to the inner reducer and the result is [3]; a bare outer lambda name still refers to its DSL binding.
Overview
monSQLize's unified expression system supports 122 operators (100% MongoDB support), covering all operations such as strings, mathematics, arrays, aggregations, dates, type conversions, logic, conditions, objects, collections, etc. These functions provide SQL-like syntax, making complex MongoDB aggregation queries simple and intuitive.
Core Features
- ✅ SQL-like syntax - Familiar function names such as CONCAT and UPPER
- ✅ AUTO COMPILATION - Automatically converted to MongoDB aggregate expressions
- ✅ Type Safety - Check parameter types at compile time
- ✅ Cache Optimization - Expression compilation results are automatically cached
- ✅ Cross-database - Support MySQL, PostgreSQL in the future
Quick example
String functions (12)
CONCAT - String concatenation
Syntax: CONCAT(str1, str2, ...)
Description: Concatenate multiple strings
Parameters:
str1, str2, ...- the string to concatenate (can be a field reference or a literal)
Example:
UPPER - Convert to uppercase
Syntax: UPPER(str)
Description: Convert string to uppercase
Parameters:
str- string field or value
Example:
LOWER - Convert to lowercase
Syntax: LOWER(str)
Description: Convert string to lowercase
Example:
TRIM - remove leading and trailing spaces
Syntax: TRIM(str)
Description: Remove spaces from the beginning and end of the string
Example:
LTRIM - Remove left spaces
Syntax: LTRIM(str)
Description: Remove spaces on the left side of the string
Example:
RTRIM - remove spaces on the right
Syntax: RTRIM(str)
Description: Remove spaces on the right side of the string
Example:
SUBSTR - substring extraction
Syntax: SUBSTR(str, start, length)
Description: Extract substring (based on bytes)
Parameters:
str- source stringstart- starting position (starting from 0)length- Extract length
Example:
SUBSTR_CP - Substring extraction (Unicode)
Syntax: SUBSTR_CP(str, start, length)
Description: Extract substring (based on Unicode code points)
Example:
LENGTH - String length
Syntax: LENGTH(str)
Description: Get the string length (Unicode code points)
Example:
SPLIT - String splitting
Syntax: SPLIT(str, delimiter)
Description: Split the string into an array
Parameters:
str- the string to splitdelimiter- delimiter
Example:
REPLACE - string replacement
Syntax: REPLACE(str, find, replacement)
Description: Replace all matches in a string
Parameters:
str- source stringfind- the string to findreplacement- Replacement content
Example:
INDEX_OF_STR - String search
Syntax: INDEX_OF_STR(str, substring)
Description: Find the position of the substring (returns the byte index)
Example:
Math functions (6)
ABS - Absolute value
Syntax: ABS(number)
Description: Returns the absolute value of the number
Example:
CEIL - Round up
Syntax: CEIL(number)
Description: Round up to the nearest integer
Example:
FLOOR - round down
Syntax: FLOOR(number)
Description: Round down to the nearest integer
Example:
ROUND - round up
Syntax: ROUND(number)
Description: Round to the nearest whole number
Example:
SQRT - square root
Syntax: SQRT(number)
Description: Returns the square root
Example:
POW - Exponentiation
Syntax: POW(base, exponent)
Description: Returns the exponent power of base
Parameters:
base- baseexponent- Index
Example:
Array functions (10)
SIZE - array size
Syntax: SIZE(array)
Description: Returns the number of elements in the array
Example:
FIRST - the first element of the array
Syntax: FIRST(array)
Description: Returns the first element of the array
Example:
LAST - the last element of the array
Syntax: LAST(array)
Description: Returns the last element of the array
Example:
SLICE - array slice
Syntax: SLICE(array, start, length)
Description: Extract part of the array
Parameters:
array- source arraystart- starting positionlength- Extract quantity
Example:
ARRAY_ELEM_AT - Get array elements
Syntax: ARRAY_ELEM_AT(array, index)
Description: Get the element at the specified position in the array
Parameters:
array- arrayindex- index (supports negative numbers, -1 indicates the last one)
Example:
IN - Array contains check
Syntax: IN(value, array)
Description: Check if the value is in the array
Example:
FILTER - Array filtering
Syntax: FILTER(array, varName, condition)
Description: Filter array elements
Parameters:
array- source arrayvarName- loop variable namecondition- filter conditions
Example:
MAP - Array mapping
Syntax: MAP(array, varName, expression)
Description: Apply an expression to each element of the array
Example:
INDEX_OF - array search
Syntax: INDEX_OF(array, value)
Description: Find the index position of the value in the array
Example:
CONCAT_ARRAYS - Array concatenation
Syntax: CONCAT_ARRAYS(array1, array2, ...)
Description: Connect multiple arrays
Example:
Aggregation functions (7)
SUM - Sum
Syntax: SUM(field) or SUM()
Description: Calculate the sum of fields, and return the count if there are no parameters.
Example:
AVG - Average
Syntax: AVG(field)
Description: Calculate the average
Example:
MAX - Maximum value
Syntax: MAX(field)
Description: Get the maximum value
Example:
MIN - Minimum value
Syntax: MIN(field)
Description: Get the minimum value
Example:
COUNT - count
Syntax: COUNT()
Description: Calculate the number of documents
Example:
PUSH - Build an array
Syntax: PUSH(field)
Description: Collect field values into an array
Example:
ADD_TO_SET - Construct a unique array
Syntax: ADD_TO_SET(field)
Description: Collect field values into an array (remove duplication)
Example:
Date functions (6)
YEAR - Get the year
Syntax: YEAR(date)
Description: Extract year from date
Example:
MONTH - Get the month
Syntax: MONTH(date)
Description: Extract the month (1-12) from the date
Example:
DAY_OF_MONTH - Get the date
Syntax: DAY_OF_MONTH(date)
Description: Extract the day (1-31) from the date
Example:
HOUR - Get the hour
Syntax: HOUR(date)
Description: Extract the hour (0-23) from the date
Example:
MINUTE - Get minutes
Syntax: MINUTE(date)
Description: Extract minutes (0-59) from date
Example:
SECOND - Get seconds
Syntax: SECOND(date)
Description: Extract seconds (0-59) from date
Example:
DATE_ADD - Date addition 🆕 v1.1.0
Syntax: DATE_ADD(date, amount, unit)
Description: Add the date and return the new date
Parameters:
date- start date fieldamount- quantity (number or field reference)unit- time unit ("year","month","week","day","hour","minute","second","millisecond")
MongoDB Version: Requires MongoDB 5.0+
Example:
Usage Scenario:
- Calculate delivery date
- Calculate renewal date
- Calculate expiry time
- Calculate reminder time
DATE_SUBTRACT - Date subtraction 🆕 v1.1.0
Syntax: DATE_SUBTRACT(date, amount, unit)
Description: Subtract the date and return the new date
Parameters:
date- start date fieldamount- quantity (number or field reference)unit- time unit (same as DATE_ADD)
MongoDB Version: Requires MongoDB 5.0+
Example:
Usage Scenario:
- Calculate advance reminder date
- Calculate refund deadline
- Calculate historical time points
DATE_DIFF - Date difference calculation 🆕 v1.1.0
Syntax: DATE_DIFF(endDate, startDate, unit)
Description: Calculate the difference between two dates
Parameters:
endDate- end datestartDate- start dateunit- return value unit (same as DATE_ADD)
MongoDB Version: Requires MongoDB 5.0+
Example:
Usage Scenario:
- Calculate order processing time
- Calculate the number of days a user is active
- Calculate the remaining days of membership
- Performance analysis and statistics
DATE_TO_STRING - Date formatting 🆕 v1.1.0
Syntax: DATE_TO_STRING(date, format)
Description: Format date into string
Parameters:
date- Date fieldformat- format template (using MongoDB format characters)
Supported format characters:
%Y- year (4 digits, such as 2026)%m- Month (01-12)%d- Day (01-31)%H- hour (00-23)%M- points (00-59)%S- seconds (00-59)
MongoDB version: Support MongoDB 3.6+
Example:
Usage Scenario:
- Formatted date display
- Generate reports
- Export data
- API returns formatted date
DATE_FROM_STRING - String parsing 🆕 v1.1.0
Syntax: DATE_FROM_STRING(dateString [, format])
Description: Parse a string into a date object
Parameters:
dateString- date string field or literalformat- optional, format template (default ISO 8601)
MongoDB version: Support MongoDB 3.6+
Example:
Usage Scenario:
- Data import
- Parse text date
- Date field standardization
- Data cleaning
Types and logical functions (5)
TYPE - Get the type
Syntax: TYPE(value)
Description: BSON type of return value
Example:
NOT - logical negation
Syntax: NOT(expression)
Description: Negate the expression result
Example:
EXISTS - Existence check
Syntax: EXISTS(field)
Description: Check whether the field exists (not null)
Example:
IS_NUMBER - Numeric type check
Syntax: IS_NUMBER(value)
Description: Check whether the value is a numeric type
Example:
IS_ARRAY - Array type check
Syntax: IS_ARRAY(value)
Description: Check whether the value is an array
Example:
Advanced operation functions (7)
REGEX - regular matching
Syntax: REGEX(field, pattern)
Description: Use regular expressions to match strings
Parameters:
field- field namepattern- Regular expression pattern
Example:
MERGE_OBJECTS - Merge objects
Syntax: MERGE_OBJECTS(obj1, obj2, ...)
Description: Merge multiple objects
Example:
TO_INT - Convert to integer
Syntax: TO_INT(value)
Description: Convert value to integer
Example:
TO_STRING - Convert to string
Syntax: TO_STRING(value)
Description: Convert value to string
Example:
OBJECT_TO_ARRAY - object to array
Syntax: OBJECT_TO_ARRAY(obj)
Description: Convert the object to an array of key-value pairs
Example:
ARRAY_TO_OBJECT - Array to object
Syntax: ARRAY_TO_OBJECT(array)
Description: Convert an array of key-value pairs to an object
Example:
SET_UNION - Set union
Syntax: SET_UNION(array1, array2, ...)
Description: Return the union of multiple arrays (remove duplication)
Example:
Conditional function (1)
SWITCH - Multi-condition judgment
Syntax: SWITCH(case1, result1, case2, result2, ..., default)
Description: Multi-condition judgment similar to switch-case
Example:
Function index table
Usage example
Example 1: User classification
Example 2: Calculate discount price
Example 3: Data aggregation
Example 4: Array processing
Example 5: String processing
Performance recommendations
1. Use index
2. Avoid complex nesting
3. Use cache
4. Reasonable use of $match
Related documents
Supplementary instructions
API alias
expr is the abbreviated alias of createExpression. The two are completely equivalent, and it is recommended to use the short expr: