Skip to content

feat($slice): array slicing operator, both arities#6

Merged
douglasjordan2 merged 1 commit into
mainfrom
feature/slice-operator
Jun 12, 2026
Merged

feat($slice): array slicing operator, both arities#6
douglasjordan2 merged 1 commit into
mainfrom
feature/slice-operator

Conversation

@douglasjordan2

Copy link
Copy Markdown
Owner

Summary

Implements MongoDB's $slice expression operator (#2), both forms:

  • { $slice: ["$arr", n] } — first n elements, or last |n| when n is negative
  • { $slice: ["$arr", skip, n] }n elements starting at skip; negative skip counts from the end and clamps at the start, matching Mongo semantics

Both compile to a jsonb_array_elements ... WITH ORDINALITY subquery re-aggregated with jsonb_agg(e ORDER BY ord) so element order is preserved. All user-supplied values stay parameterized.

Tests

  • 2 unit tests asserting SQL shape (ordinality window, ordered agg, skip/take bounds, parameterized values)
  • 2 integration tests running $slice in $project and $addFields against real Postgres: first-n, last-n, n past length, zero n, skip+take, negative position, position past start
  • 88 pass / 0 fail, tsc --noEmit clean

README expression list updated.

Closes #2

🤖 Generated with Claude Code

Adds $slice to the expression ops table. Both Mongo forms compile to a
jsonb_array_elements ... WITH ORDINALITY subquery re-aggregated with
jsonb_agg(e order by ord) so element order is preserved:

- [arr, n]: ord <= n for positive n; for negative n, last |n| via
  ord > jsonb_array_length(arr) + n.
- [arr, skip, n]: start = greatest(case when skip < 0 then len + skip
  else skip end, 0), take ord in (start, start + n]. Negative skip
  counts from the end and clamps at 0, matching Mongo.

Tests: 2 unit (SQL shape: ordinality window, ordered agg, skip/take
bounds, params) + 2 integration in $project and $addFields covering
first-n, last-n, n past length, zero n, skip+take, negative position,
position past start. README expression list updated.

88 pass / 0 fail. tsc clean.

Closes #2

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@douglasjordan2 douglasjordan2 merged commit e5ef449 into main Jun 12, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add $slice operator for arrays

1 participant