@zodmon/core 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { ObjectId, FindCursor, Collection, MongoClientOptions } from 'mongodb';
1
+ import { ObjectId, DeleteResult, FindCursor, Collection, UpdateResult, MongoClientOptions } from 'mongodb';
2
2
  import { ZodPipe, ZodCustom, ZodTransform, z, ZodDefault } from 'zod';
3
3
 
4
4
  /**
@@ -134,32 +134,6 @@ declare module 'zod' {
134
134
  * ```
135
135
  */
136
136
  declare function getIndexMetadata(schema: unknown): IndexMetadata | undefined;
137
- /**
138
- * Monkey-patch Zod's `ZodType.prototype` with Zodmon extension methods
139
- * (`.index()`, `.unique()`, `.text()`, `.expireAfter()`).
140
- *
141
- * In Zod v4, methods are copied from `ZodType.prototype` to each instance
142
- * during construction via the internal `init` loop (`Object.keys(proto)` ->
143
- * copy to instance). Extension methods use `enumerable: true` so they are
144
- * picked up by this loop for every schema created after installation.
145
- *
146
- * The function is idempotent: calling it more than once is a safe no-op,
147
- * guarded by a non-enumerable `Symbol.for('zodmon_extensions')` property
148
- * on the prototype.
149
- *
150
- * This function is called at module level when `extensions.ts` is first
151
- * imported, so consumers never need to call it manually. It is exported
152
- * primarily for use in tests.
153
- *
154
- * @example
155
- * ```ts
156
- * import { installExtensions } from '@zodmon/core/schema/extensions'
157
- * installExtensions() // safe to call multiple times
158
- *
159
- * const indexed = z.string().index({ unique: true })
160
- * ```
161
- */
162
- declare function installExtensions(): void;
163
137
 
164
138
  /**
165
139
  * The Zod type produced by {@link objectId}. A pipeline that validates an
@@ -290,6 +264,281 @@ type CollectionDefinition<TShape extends z.core.$ZodShape = z.core.$ZodShape> =
290
264
  /** Erased collection type for use in generic contexts. */
291
265
  type AnyCollection = CollectionDefinition<z.core.$ZodShape>;
292
266
 
267
+ /**
268
+ * Comparison operators for a field value of type `V`.
269
+ *
270
+ * Maps each MongoDB comparison operator to its expected value type.
271
+ * `$regex` is only available when `V` extends `string`.
272
+ *
273
+ * Used as the operator object that can be assigned to a field in {@link TypedFilter}.
274
+ *
275
+ * @example
276
+ * ```ts
277
+ * // As a raw object (without builder functions)
278
+ * const filter: TypedFilter<User> = { age: { $gt: 25, $lte: 65 } }
279
+ *
280
+ * // $regex only available on string fields
281
+ * const filter: TypedFilter<User> = { name: { $regex: /^A/i } }
282
+ * ```
283
+ */
284
+ type ComparisonOperators<V> = {
285
+ /** Matches values equal to the specified value. */
286
+ $eq?: V;
287
+ /** Matches values not equal to the specified value. */
288
+ $ne?: V;
289
+ /** Matches values greater than the specified value. */
290
+ $gt?: V;
291
+ /** Matches values greater than or equal to the specified value. */
292
+ $gte?: V;
293
+ /** Matches values less than the specified value. */
294
+ $lt?: V;
295
+ /** Matches values less than or equal to the specified value. */
296
+ $lte?: V;
297
+ /** Matches any value in the specified array. */
298
+ $in?: V[];
299
+ /** Matches none of the values in the specified array. */
300
+ $nin?: V[];
301
+ /** Matches documents where the field exists (`true`) or does not exist (`false`). */
302
+ $exists?: boolean;
303
+ /** Negates a comparison operator. */
304
+ $not?: ComparisonOperators<V>;
305
+ } & (V extends string ? {
306
+ $regex?: RegExp | string;
307
+ } : unknown);
308
+ /** Depth counter for limiting dot-notation recursion. Index = current depth, value = next depth. */
309
+ type Prev = [never, 0, 1, 2];
310
+ /**
311
+ * Generates a union of all valid dot-separated paths for nested object fields in `T`.
312
+ *
313
+ * Recursion is limited to 3 levels deep to prevent TypeScript compilation performance issues.
314
+ * Only plain object fields are traversed — arrays, `Date`, `RegExp`, and `ObjectId` are
315
+ * treated as leaf nodes and do not produce sub-paths.
316
+ *
317
+ * @example
318
+ * ```ts
319
+ * type User = { address: { city: string; geo: { lat: number; lng: number } } }
320
+ *
321
+ * // DotPaths<User> = 'address.city' | 'address.geo' | 'address.geo.lat' | 'address.geo.lng'
322
+ * ```
323
+ */
324
+ type DotPaths<T, Depth extends number = 3> = Depth extends 0 ? never : {
325
+ [K in keyof T & string]: NonNullable<T[K]> extends ReadonlyArray<unknown> | Date | RegExp | ObjectId ? never : NonNullable<T[K]> extends Record<string, unknown> ? `${K}.${keyof NonNullable<T[K]> & string}` | `${K}.${DotPaths<NonNullable<T[K]>, Prev[Depth]>}` : never;
326
+ }[keyof T & string];
327
+ /**
328
+ * Resolves the value type at a dot-separated path `P` within type `T`.
329
+ *
330
+ * Splits `P` on the first `.` and recursively descends into `T`'s nested types.
331
+ * Returns `never` if the path is invalid.
332
+ *
333
+ * @example
334
+ * ```ts
335
+ * type User = { address: { city: string; geo: { lat: number } } }
336
+ *
337
+ * // DotPathType<User, 'address.city'> = string
338
+ * // DotPathType<User, 'address.geo.lat'> = number
339
+ * ```
340
+ */
341
+ type DotPathType<T, P extends string> = P extends `${infer K}.${infer Rest}` ? K extends keyof T ? Rest extends keyof NonNullable<T[K]> ? NonNullable<T[K]>[Rest] : DotPathType<NonNullable<T[K]>, Rest> : never : P extends keyof T ? T[P] : never;
342
+ /**
343
+ * Strict type-safe MongoDB filter query type.
344
+ *
345
+ * Validates filter objects at compile time — rejects nonexistent fields, type mismatches,
346
+ * and invalid operator usage. Unlike the MongoDB driver's `Filter<T>`, does NOT allow
347
+ * arbitrary keys via `& Document`.
348
+ *
349
+ * Supports three forms of filter expressions:
350
+ * - **Direct field values** (implicit `$eq`): `{ name: 'Alice' }`
351
+ * - **Comparison operators**: `{ age: { $gt: 25 } }` or `{ age: $gt(25) }`
352
+ * - **Dot notation** for nested fields up to 3 levels: `{ 'address.city': 'NYC' }`
353
+ *
354
+ * Logical operators `$and`, `$or`, and `$nor` accept arrays of `TypedFilter<T>`
355
+ * for composing complex queries.
356
+ *
357
+ * @example
358
+ * ```ts
359
+ * // Simple equality
360
+ * const filter: TypedFilter<User> = { name: 'Alice' }
361
+ *
362
+ * // Builder functions mixed with object literals
363
+ * const filter: TypedFilter<User> = { age: $gte(18), role: $in(['admin', 'mod']) }
364
+ *
365
+ * // Logical composition — T inferred from find() context
366
+ * posts.find($and(
367
+ * $or({ published: true }, { views: $gte(100) }),
368
+ * { title: $regex(/guide/i) },
369
+ * ))
370
+ *
371
+ * // Dynamic conditional building
372
+ * const conditions: TypedFilter<User>[] = []
373
+ * if (name) conditions.push({ name })
374
+ * if (minAge) conditions.push({ age: $gte(minAge) })
375
+ * const filter = conditions.length ? $and<User>(...conditions) : {}
376
+ * ```
377
+ */
378
+ type TypedFilter<T> = {
379
+ [K in keyof T]?: T[K] | ComparisonOperators<T[K]>;
380
+ } & {
381
+ [P in DotPaths<T>]?: DotPathType<T, P> | ComparisonOperators<DotPathType<T, P>>;
382
+ } & {
383
+ /** Joins clauses with a logical AND. Matches documents that satisfy all filters. */
384
+ $and?: TypedFilter<T>[];
385
+ /** Joins clauses with a logical OR. Matches documents that satisfy at least one filter. */
386
+ $or?: TypedFilter<T>[];
387
+ /** Joins clauses with a logical NOR. Matches documents that fail all filters. */
388
+ $nor?: TypedFilter<T>[];
389
+ };
390
+
391
+ /**
392
+ * Options for {@link findOneAndDelete}.
393
+ */
394
+ type FindOneAndDeleteOptions = {
395
+ /** Override the collection-level validation mode, or `false` to skip validation entirely. */
396
+ validate?: ValidationMode | false;
397
+ };
398
+ /**
399
+ * Delete a single document matching the filter.
400
+ *
401
+ * Removes the first document that matches the filter from the collection.
402
+ * No validation is performed — the document is deleted directly through
403
+ * the MongoDB driver.
404
+ *
405
+ * @param handle - The collection handle to delete from.
406
+ * @param filter - Type-safe filter to match documents.
407
+ * @returns The MongoDB `DeleteResult` with the deleted count.
408
+ *
409
+ * @example
410
+ * ```ts
411
+ * const result = await deleteOne(users, { name: 'Ada' })
412
+ * console.log(result.deletedCount) // 1
413
+ * ```
414
+ */
415
+ declare function deleteOne<TDef extends AnyCollection>(handle: CollectionHandle<TDef>, filter: TypedFilter<InferDocument<TDef>>): Promise<DeleteResult>;
416
+ /**
417
+ * Delete all documents matching the filter.
418
+ *
419
+ * Removes every document that matches the filter from the collection.
420
+ * No validation is performed — documents are deleted directly through
421
+ * the MongoDB driver.
422
+ *
423
+ * @param handle - The collection handle to delete from.
424
+ * @param filter - Type-safe filter to match documents.
425
+ * @returns The MongoDB `DeleteResult` with the deleted count.
426
+ *
427
+ * @example
428
+ * ```ts
429
+ * const result = await deleteMany(users, { role: 'guest' })
430
+ * console.log(result.deletedCount) // number of guests removed
431
+ * ```
432
+ */
433
+ declare function deleteMany<TDef extends AnyCollection>(handle: CollectionHandle<TDef>, filter: TypedFilter<InferDocument<TDef>>): Promise<DeleteResult>;
434
+ /**
435
+ * Find a single document matching the filter, delete it, and return the document.
436
+ *
437
+ * Returns the deleted document, or `null` if no document matches the filter.
438
+ * The returned document is validated against the collection's Zod schema
439
+ * using the same resolution logic as {@link findOne}.
440
+ *
441
+ * @param handle - The collection handle to delete from.
442
+ * @param filter - Type-safe filter to match documents.
443
+ * @param options - Optional settings: `validate`.
444
+ * @returns The deleted document, or `null` if no document matches.
445
+ * @throws {ZodmonValidationError} When the returned document fails schema validation in strict mode.
446
+ *
447
+ * @example
448
+ * ```ts
449
+ * const user = await findOneAndDelete(users, { name: 'Ada' })
450
+ * if (user) console.log(user.name) // 'Ada' (the deleted document)
451
+ * ```
452
+ *
453
+ * @example
454
+ * ```ts
455
+ * const user = await findOneAndDelete(
456
+ * users,
457
+ * { role: 'guest' },
458
+ * { validate: false },
459
+ * )
460
+ * ```
461
+ */
462
+ declare function findOneAndDelete<TDef extends AnyCollection>(handle: CollectionHandle<TDef>, filter: TypedFilter<InferDocument<TDef>>, options?: FindOneAndDeleteOptions): Promise<InferDocument<TDef> | null>;
463
+
464
+ /**
465
+ * Options for offset-based pagination.
466
+ *
467
+ * @example
468
+ * ```ts
469
+ * await users.find({}).sort({ name: 1 }).paginate({ page: 2, perPage: 10 })
470
+ * ```
471
+ */
472
+ type OffsetPaginateOptions = {
473
+ /** The page number to retrieve (1-indexed). */
474
+ page: number;
475
+ /** The number of documents per page. */
476
+ perPage: number;
477
+ };
478
+ /**
479
+ * Options for cursor-based pagination.
480
+ *
481
+ * @example
482
+ * ```ts
483
+ * const first = await users.find({}).sort({ name: 1 }).paginate({ limit: 10 })
484
+ * const next = await users.find({}).sort({ name: 1 }).paginate({ cursor: first.endCursor, limit: 10 })
485
+ * ```
486
+ */
487
+ type CursorPaginateOptions = {
488
+ /** Maximum number of documents to return. */
489
+ limit: number;
490
+ /** Opaque cursor string from a previous `startCursor` or `endCursor`. */
491
+ cursor?: string | null;
492
+ };
493
+ /**
494
+ * Result of offset-based pagination.
495
+ *
496
+ * @example
497
+ * ```ts
498
+ * const page = await users.find({}).paginate({ page: 1, perPage: 10 })
499
+ * console.log(page.total, page.totalPages, page.hasNext)
500
+ * ```
501
+ */
502
+ type OffsetPage<TDoc> = {
503
+ /** The documents for this page. */
504
+ docs: TDoc[];
505
+ /** Total number of matching documents. */
506
+ total: number;
507
+ /** Current page number (1-indexed). */
508
+ page: number;
509
+ /** Number of documents per page. */
510
+ perPage: number;
511
+ /** Total number of pages (`Math.ceil(total / perPage)`). */
512
+ totalPages: number;
513
+ /** Whether there is a next page. */
514
+ hasNext: boolean;
515
+ /** Whether there is a previous page. */
516
+ hasPrev: boolean;
517
+ };
518
+ /**
519
+ * Result of cursor-based pagination.
520
+ *
521
+ * @example
522
+ * ```ts
523
+ * const page = await users.find({}).paginate({ limit: 10 })
524
+ * if (page.hasNext) {
525
+ * const next = await users.find({}).paginate({ cursor: page.endCursor, limit: 10 })
526
+ * }
527
+ * ```
528
+ */
529
+ type CursorPage<TDoc> = {
530
+ /** The documents for this page. */
531
+ docs: TDoc[];
532
+ /** Whether there are more documents after this page. */
533
+ hasNext: boolean;
534
+ /** Whether there are documents before this page. */
535
+ hasPrev: boolean;
536
+ /** Cursor for the first document (pass to `cursor` to go backward). `null` when empty. */
537
+ startCursor: string | null;
538
+ /** Cursor for the last document (pass to `cursor` to go forward). `null` when empty. */
539
+ endCursor: string | null;
540
+ };
541
+
293
542
  /**
294
543
  * Type-safe sort specification for a document type.
295
544
  *
@@ -332,7 +581,13 @@ declare class TypedFindCursor<TDef extends AnyCollection> {
332
581
  /** @internal */
333
582
  private mode;
334
583
  /** @internal */
335
- constructor(cursor: FindCursor<InferDocument<TDef>>, definition: TDef, mode: ValidationMode | false);
584
+ private readonly nativeCollection;
585
+ /** @internal */
586
+ private readonly filter;
587
+ /** @internal */
588
+ private sortSpec;
589
+ /** @internal */
590
+ constructor(cursor: FindCursor<InferDocument<TDef>>, definition: TDef, mode: ValidationMode | false, nativeCollection: Collection<InferDocument<TDef>>, filter: any);
336
591
  /**
337
592
  * Set the sort order for the query.
338
593
  *
@@ -372,6 +627,51 @@ declare class TypedFindCursor<TDef extends AnyCollection> {
372
627
  * ```
373
628
  */
374
629
  limit(n: number): this;
630
+ /**
631
+ * Execute the query with offset-based pagination, returning a page of documents
632
+ * with total count and navigation metadata.
633
+ *
634
+ * Runs `countDocuments` and `find` in parallel for performance. Ignores any
635
+ * `.skip()` or `.limit()` already set on the cursor — issues a fresh query.
636
+ *
637
+ * @param opts - Offset pagination options: `page` (1-indexed) and `perPage`.
638
+ * @returns A page with `docs`, `total`, `totalPages`, `hasNext`, `hasPrev`.
639
+ * @throws {ZodmonValidationError} When a document fails schema validation.
640
+ *
641
+ * @example
642
+ * ```ts
643
+ * const page = await users.find({ role: 'admin' })
644
+ * .sort({ createdAt: -1 })
645
+ * .paginate({ page: 2, perPage: 10 })
646
+ * console.log(page.total, page.totalPages, page.hasNext)
647
+ * ```
648
+ */
649
+ paginate(opts: OffsetPaginateOptions): Promise<OffsetPage<InferDocument<TDef>>>;
650
+ /**
651
+ * Execute the query with cursor-based pagination, returning a page of documents
652
+ * with opaque cursors for forward/backward navigation.
653
+ *
654
+ * Uses the `limit + 1` trick to determine `hasNext`/`hasPrev` without extra queries.
655
+ * Direction is encoded in the cursor — pass `endCursor` to go forward, `startCursor`
656
+ * to go backward.
657
+ *
658
+ * @param opts - Cursor pagination options: `limit` and optional `cursor`.
659
+ * @returns A page with `docs`, `hasNext`, `hasPrev`, `startCursor`, `endCursor`.
660
+ * @throws {ZodmonValidationError} When a document fails schema validation.
661
+ * @throws {Error} When the cursor string is malformed.
662
+ *
663
+ * @example
664
+ * ```ts
665
+ * const first = await users.find({}).sort({ name: 1 }).paginate({ limit: 10 })
666
+ * const next = await users.find({}).sort({ name: 1 })
667
+ * .paginate({ cursor: first.endCursor, limit: 10 })
668
+ * ```
669
+ */
670
+ paginate(opts: CursorPaginateOptions): Promise<CursorPage<InferDocument<TDef>>>;
671
+ /** @internal Offset pagination implementation. */
672
+ private offsetPaginate;
673
+ /** @internal Cursor pagination implementation. */
674
+ private cursorPaginate;
375
675
  /**
376
676
  * Execute the query and return all matching documents as an array.
377
677
  *
@@ -409,217 +709,400 @@ declare class TypedFindCursor<TDef extends AnyCollection> {
409
709
  }
410
710
 
411
711
  /**
412
- * Comparison operators for a field value of type `V`.
712
+ * Options for {@link findOne} and {@link findOneOrThrow}.
713
+ */
714
+ type FindOneOptions = {
715
+ /** MongoDB projection — include (`1`) or exclude (`0`) fields. Typed projections deferred to v1.0. */
716
+ project?: Record<string, 0 | 1>;
717
+ /** Override the collection-level validation mode, or `false` to skip validation entirely. */
718
+ validate?: ValidationMode | false;
719
+ };
720
+ /**
721
+ * Find a single document matching the filter.
413
722
  *
414
- * Maps each MongoDB comparison operator to its expected value type.
415
- * `$regex` is only available when `V` extends `string`.
723
+ * Queries MongoDB, then validates the fetched document against the collection's
724
+ * Zod schema. Validation mode is resolved from the per-query option, falling
725
+ * back to the collection-level default (which defaults to `'strict'`).
416
726
  *
417
- * Used as the operator object that can be assigned to a field in {@link TypedFilter}.
727
+ * @param handle - The collection handle to query.
728
+ * @param filter - Type-safe filter to match documents.
729
+ * @param options - Optional projection and validation overrides.
730
+ * @returns The matched document, or `null` if no document matches.
731
+ * @throws {ZodmonValidationError} When the fetched document fails schema validation in strict mode.
418
732
  *
419
733
  * @example
420
734
  * ```ts
421
- * // As a raw object (without builder functions)
422
- * const filter: TypedFilter<User> = { age: { $gt: 25, $lte: 65 } }
735
+ * const user = await findOne(users, { name: 'Ada' })
736
+ * if (user) console.log(user.role) // typed as 'admin' | 'user'
737
+ * ```
738
+ */
739
+ declare function findOne<TDef extends AnyCollection>(handle: CollectionHandle<TDef>, filter: TypedFilter<InferDocument<TDef>>, options?: FindOneOptions): Promise<InferDocument<TDef> | null>;
740
+ /**
741
+ * Find a single document matching the filter, or throw if none exists.
423
742
  *
424
- * // $regex only available on string fields
425
- * const filter: TypedFilter<User> = { name: { $regex: /^A/i } }
743
+ * Behaves identically to {@link findOne} but throws {@link ZodmonNotFoundError}
744
+ * instead of returning `null` when no document matches the filter.
745
+ *
746
+ * @param handle - The collection handle to query.
747
+ * @param filter - Type-safe filter to match documents.
748
+ * @param options - Optional projection and validation overrides.
749
+ * @returns The matched document (never null).
750
+ * @throws {ZodmonNotFoundError} When no document matches the filter.
751
+ * @throws {ZodmonValidationError} When the fetched document fails schema validation in strict mode.
752
+ *
753
+ * @example
754
+ * ```ts
755
+ * const user = await findOneOrThrow(users, { name: 'Ada' })
756
+ * console.log(user.role) // typed as 'admin' | 'user', guaranteed non-null
426
757
  * ```
427
758
  */
428
- type ComparisonOperators<V> = {
429
- /** Matches values equal to the specified value. */
430
- $eq?: V;
431
- /** Matches values not equal to the specified value. */
432
- $ne?: V;
433
- /** Matches values greater than the specified value. */
434
- $gt?: V;
435
- /** Matches values greater than or equal to the specified value. */
436
- $gte?: V;
437
- /** Matches values less than the specified value. */
438
- $lt?: V;
439
- /** Matches values less than or equal to the specified value. */
440
- $lte?: V;
441
- /** Matches any value in the specified array. */
442
- $in?: V[];
443
- /** Matches none of the values in the specified array. */
444
- $nin?: V[];
445
- /** Matches documents where the field exists (`true`) or does not exist (`false`). */
446
- $exists?: boolean;
447
- /** Negates a comparison operator. */
448
- $not?: ComparisonOperators<V>;
449
- } & (V extends string ? {
450
- $regex?: RegExp | string;
451
- } : unknown);
452
- /** Depth counter for limiting dot-notation recursion. Index = current depth, value = next depth. */
453
- type Prev = [never, 0, 1, 2];
759
+ declare function findOneOrThrow<TDef extends AnyCollection>(handle: CollectionHandle<TDef>, filter: TypedFilter<InferDocument<TDef>>, options?: FindOneOptions): Promise<InferDocument<TDef>>;
760
+ /**
761
+ * Options for {@link find}.
762
+ */
763
+ type FindOptions = {
764
+ /** Override the collection-level validation mode, or `false` to skip validation entirely. */
765
+ validate?: ValidationMode | false;
766
+ };
767
+ /**
768
+ * Find all documents matching the filter, returning a chainable typed cursor.
769
+ *
770
+ * The cursor is lazy no query is executed until a terminal method
771
+ * (`toArray`, `for await`) is called. Use `sort`, `skip`, and `limit`
772
+ * to shape the query before executing.
773
+ *
774
+ * Each document is validated against the collection's Zod schema when
775
+ * a terminal method consumes it.
776
+ *
777
+ * @param handle - The collection handle to query.
778
+ * @param filter - Type-safe filter to match documents.
779
+ * @param options - Optional validation overrides.
780
+ * @returns A typed cursor for chaining query modifiers.
781
+ *
782
+ * @example
783
+ * ```ts
784
+ * const admins = await find(users, { role: 'admin' })
785
+ * .sort({ name: 1 })
786
+ * .limit(10)
787
+ * .toArray()
788
+ * ```
789
+ *
790
+ * @example
791
+ * ```ts
792
+ * for await (const user of find(users, {})) {
793
+ * console.log(user.name)
794
+ * }
795
+ * ```
796
+ */
797
+ declare function find<TDef extends AnyCollection>(handle: CollectionHandle<TDef>, filter: TypedFilter<InferDocument<TDef>>, options?: FindOptions): TypedFindCursor<TDef>;
798
+
799
+ /**
800
+ * Extracts the element type from an array type.
801
+ *
802
+ * @example
803
+ * ```ts
804
+ * type E = ArrayElement<string[]> // string
805
+ * type N = ArrayElement<number[]> // number
806
+ * ```
807
+ */
808
+ type ArrayElement<T> = T extends ReadonlyArray<infer E> ? E : never;
809
+ /**
810
+ * Fields valid for `$set`, `$setOnInsert`, `$min`, and `$max` operators.
811
+ *
812
+ * Allows top-level fields with matching value types plus dot-notation paths
813
+ * for nested field updates.
814
+ *
815
+ * @example
816
+ * ```ts
817
+ * const set: SetFields<User> = { name: 'Alice', 'address.city': 'NYC' }
818
+ * ```
819
+ */
820
+ type SetFields<T> = {
821
+ [K in keyof T]?: T[K];
822
+ } & {
823
+ [P in DotPaths<T>]?: DotPathType<T, P>;
824
+ };
825
+ /**
826
+ * Fields valid for the `$inc` operator — only number-typed fields.
827
+ *
828
+ * Includes dot-notation paths that resolve to number types.
829
+ *
830
+ * @example
831
+ * ```ts
832
+ * const inc: IncFields<User> = { age: 1, 'stats.views': 5 }
833
+ * ```
834
+ */
835
+ type IncFields<T> = {
836
+ [K in keyof T as NonNullable<T[K]> extends number ? K : never]?: number;
837
+ } & {
838
+ [P in DotPaths<T> as DotPathType<T, P> extends number ? P : never]?: number;
839
+ };
840
+ /**
841
+ * Modifiers for the `$push` operator.
842
+ *
843
+ * Use with `$push` to insert multiple elements and control array position/size.
844
+ *
845
+ * @example
846
+ * ```ts
847
+ * const push = { tags: { $each: ['a', 'b'], $position: 0, $slice: 10 } }
848
+ * ```
849
+ */
850
+ type PushModifiers<E> = {
851
+ /** Array of elements to push. */
852
+ $each: E[];
853
+ /** Position at which to insert elements. */
854
+ $position?: number;
855
+ /** Maximum array length after push. */
856
+ $slice?: number;
857
+ /** Sort order applied after push. */
858
+ $sort?: 1 | -1 | Record<string, 1 | -1>;
859
+ };
860
+ /**
861
+ * Fields valid for the `$push` operator — only array-typed fields.
862
+ *
863
+ * Accepts a single element value or a modifier object with `$each`.
864
+ *
865
+ * @example
866
+ * ```ts
867
+ * const push: PushFields<User> = { tags: 'dev' }
868
+ * const pushMany: PushFields<User> = { tags: { $each: ['a', 'b'] } }
869
+ * ```
870
+ */
871
+ type PushFields<T> = {
872
+ [K in keyof T as NonNullable<T[K]> extends ReadonlyArray<unknown> ? K : never]?: ArrayElement<NonNullable<T[K]>> | PushModifiers<ArrayElement<NonNullable<T[K]>>>;
873
+ };
874
+ /**
875
+ * Fields valid for the `$pull` operator — only array-typed fields.
876
+ *
877
+ * For primitive arrays: accepts a value or comparison operators.
878
+ * For object arrays: also accepts a `TypedFilter` on the element type.
879
+ *
880
+ * @example
881
+ * ```ts
882
+ * const pull: PullFields<User> = { tags: 'old' }
883
+ * const pullQuery: PullFields<User> = { scores: { $lt: 50 } }
884
+ * const pullObj: PullFields<User> = { comments: { author: 'spam' } }
885
+ * ```
886
+ */
887
+ type PullFields<T> = {
888
+ [K in keyof T as NonNullable<T[K]> extends ReadonlyArray<unknown> ? K : never]?: ArrayElement<NonNullable<T[K]>> | ComparisonOperators<ArrayElement<NonNullable<T[K]>>> | (ArrayElement<NonNullable<T[K]>> extends Record<string, unknown> ? TypedFilter<ArrayElement<NonNullable<T[K]>>> : unknown);
889
+ };
890
+ /**
891
+ * Modifier for the `$addToSet` operator's `$each` syntax.
892
+ *
893
+ * @example
894
+ * ```ts
895
+ * const addToSet = { tags: { $each: ['a', 'b'] } }
896
+ * ```
897
+ */
898
+ type AddToSetEach<E> = {
899
+ $each: E[];
900
+ };
454
901
  /**
455
- * Generates a union of all valid dot-separated paths for nested object fields in `T`.
902
+ * Fields valid for the `$addToSet` operator only array-typed fields.
456
903
  *
457
- * Recursion is limited to 3 levels deep to prevent TypeScript compilation performance issues.
458
- * Only plain object fields are traversed — arrays, `Date`, `RegExp`, and `ObjectId` are
459
- * treated as leaf nodes and do not produce sub-paths.
904
+ * Accepts a single element value or `{ $each: [...] }` for multiple elements.
460
905
  *
461
906
  * @example
462
907
  * ```ts
463
- * type User = { address: { city: string; geo: { lat: number; lng: number } } }
464
- *
465
- * // DotPaths<User> = 'address.city' | 'address.geo' | 'address.geo.lat' | 'address.geo.lng'
908
+ * const add: AddToSetFields<User> = { tags: 'dev' }
909
+ * const addMany: AddToSetFields<User> = { tags: { $each: ['a', 'b'] } }
466
910
  * ```
467
911
  */
468
- type DotPaths<T, Depth extends number = 3> = Depth extends 0 ? never : {
469
- [K in keyof T & string]: NonNullable<T[K]> extends ReadonlyArray<unknown> | Date | RegExp | ObjectId ? never : NonNullable<T[K]> extends Record<string, unknown> ? `${K}.${keyof NonNullable<T[K]> & string}` | `${K}.${DotPaths<NonNullable<T[K]>, Prev[Depth]>}` : never;
470
- }[keyof T & string];
912
+ type AddToSetFields<T> = {
913
+ [K in keyof T as NonNullable<T[K]> extends ReadonlyArray<unknown> ? K : never]?: ArrayElement<NonNullable<T[K]>> | AddToSetEach<ArrayElement<NonNullable<T[K]>>>;
914
+ };
471
915
  /**
472
- * Resolves the value type at a dot-separated path `P` within type `T`.
916
+ * Fields valid for the `$pop` operator only array-typed fields.
473
917
  *
474
- * Splits `P` on the first `.` and recursively descends into `T`'s nested types.
475
- * Returns `never` if the path is invalid.
918
+ * Value `1` removes the last element, `-1` removes the first.
476
919
  *
477
920
  * @example
478
921
  * ```ts
479
- * type User = { address: { city: string; geo: { lat: number } } }
480
- *
481
- * // DotPathType<User, 'address.city'> = string
482
- * // DotPathType<User, 'address.geo.lat'> = number
922
+ * const pop: PopFields<User> = { tags: -1 } // remove first
483
923
  * ```
484
924
  */
485
- type DotPathType<T, P extends string> = P extends `${infer K}.${infer Rest}` ? K extends keyof T ? Rest extends keyof NonNullable<T[K]> ? NonNullable<T[K]>[Rest] : DotPathType<NonNullable<T[K]>, Rest> : never : P extends keyof T ? T[P] : never;
925
+ type PopFields<T> = {
926
+ [K in keyof T as NonNullable<T[K]> extends ReadonlyArray<unknown> ? K : never]?: 1 | -1;
927
+ };
486
928
  /**
487
- * Strict type-safe MongoDB filter query type.
929
+ * Fields valid for the `$unset` operator — any existing field.
488
930
  *
489
- * Validates filter objects at compile time rejects nonexistent fields, type mismatches,
490
- * and invalid operator usage. Unlike the MongoDB driver's `Filter<T>`, does NOT allow
491
- * arbitrary keys via `& Document`.
931
+ * Value is `''`, `true`, or `1` (all mean "remove this field").
492
932
  *
493
- * Supports three forms of filter expressions:
494
- * - **Direct field values** (implicit `$eq`): `{ name: 'Alice' }`
495
- * - **Comparison operators**: `{ age: { $gt: 25 } }` or `{ age: $gt(25) }`
496
- * - **Dot notation** for nested fields up to 3 levels: `{ 'address.city': 'NYC' }`
933
+ * @example
934
+ * ```ts
935
+ * const unset: UnsetFields<User> = { middleName: '' }
936
+ * ```
937
+ */
938
+ type UnsetFields<T> = {
939
+ [K in keyof T]?: '' | true | 1;
940
+ };
941
+ /**
942
+ * Fields valid for the `$currentDate` operator — only Date-typed fields.
497
943
  *
498
- * Logical operators `$and`, `$or`, and `$nor` accept arrays of `TypedFilter<T>`
499
- * for composing complex queries.
944
+ * Sets the field to the current date. Value is `true` or `{ $type: 'date' }`.
500
945
  *
501
946
  * @example
502
947
  * ```ts
503
- * // Simple equality
504
- * const filter: TypedFilter<User> = { name: 'Alice' }
948
+ * const cd: CurrentDateFields<User> = { createdAt: true }
949
+ * ```
950
+ */
951
+ type CurrentDateFields<T> = {
952
+ [K in keyof T as NonNullable<T[K]> extends Date ? K : never]?: true | {
953
+ $type: 'date';
954
+ };
955
+ };
956
+ /**
957
+ * Fields valid for the `$rename` operator.
505
958
  *
506
- * // Builder functions mixed with object literals
507
- * const filter: TypedFilter<User> = { age: $gte(18), role: $in(['admin', 'mod']) }
959
+ * Renames an existing field to a new name. Key is the current field name,
960
+ * value is the new name as a string.
508
961
  *
509
- * // Logical composition
510
- * const filter = $and<User>(
511
- * $or<User>({ role: 'admin' }, { role: 'moderator' }),
512
- * { age: $gte(18) },
513
- * { email: $exists() },
514
- * )
962
+ * @example
963
+ * ```ts
964
+ * const rename: RenameFields<User> = { name: 'fullName' }
965
+ * ```
966
+ */
967
+ type RenameFields<T> = {
968
+ [K in keyof T & string]?: string;
969
+ };
970
+ /**
971
+ * Strict type-safe MongoDB update filter.
515
972
  *
516
- * // Dynamic conditional building
517
- * const conditions: TypedFilter<User>[] = []
518
- * if (name) conditions.push({ name })
519
- * if (minAge) conditions.push({ age: $gte(minAge) })
520
- * const filter = conditions.length ? $and<User>(...conditions) : {}
973
+ * Validates update operators against field types at compile time. Each operator
974
+ * constrains which fields it accepts (e.g. `$inc` only on numbers, `$push` only
975
+ * on arrays). Supports dot-notation paths for nested field access.
976
+ *
977
+ * @example
978
+ * ```ts
979
+ * const update: TypedUpdateFilter<User> = {
980
+ * $set: { name: 'Alice' },
981
+ * $inc: { age: 1 },
982
+ * }
521
983
  * ```
522
984
  */
523
- type TypedFilter<T> = {
524
- [K in keyof T]?: T[K] | ComparisonOperators<T[K]>;
525
- } & {
526
- [P in DotPaths<T>]?: DotPathType<T, P> | ComparisonOperators<DotPathType<T, P>>;
527
- } & {
528
- /** Joins clauses with a logical AND. Matches documents that satisfy all filters. */
529
- $and?: TypedFilter<T>[];
530
- /** Joins clauses with a logical OR. Matches documents that satisfy at least one filter. */
531
- $or?: TypedFilter<T>[];
532
- /** Joins clauses with a logical NOR. Matches documents that fail all filters. */
533
- $nor?: TypedFilter<T>[];
985
+ type TypedUpdateFilter<T> = {
986
+ /** Sets the value of one or more fields. */
987
+ $set?: SetFields<T>;
988
+ /** Sets fields only when inserting (upsert). Same typing as `$set`. */
989
+ $setOnInsert?: SetFields<T>;
990
+ /** Increments numeric fields by the given amount. Only accepts number-typed fields. */
991
+ $inc?: IncFields<T>;
992
+ /** Updates the field if the given value is less than the current value. */
993
+ $min?: SetFields<T>;
994
+ /** Updates the field if the given value is greater than the current value. */
995
+ $max?: SetFields<T>;
996
+ /** Appends a value to an array field. Supports `$each`, `$position`, `$slice`, `$sort`. */
997
+ $push?: PushFields<T>;
998
+ /** Removes matching values from an array field. */
999
+ $pull?: PullFields<T>;
1000
+ /** Adds a value to an array only if it doesn't already exist. */
1001
+ $addToSet?: AddToSetFields<T>;
1002
+ /** Removes the first (`-1`) or last (`1`) element of an array. */
1003
+ $pop?: PopFields<T>;
1004
+ /** Removes the specified fields from the document. */
1005
+ $unset?: UnsetFields<T>;
1006
+ /** Sets the field to the current date. Only accepts Date-typed fields. */
1007
+ $currentDate?: CurrentDateFields<T>;
1008
+ /** Renames a field. */
1009
+ $rename?: RenameFields<T>;
534
1010
  };
535
1011
 
536
1012
  /**
537
- * Options for {@link findOne} and {@link findOneOrThrow}.
1013
+ * Options for {@link updateOne} and {@link updateMany}.
538
1014
  */
539
- type FindOneOptions = {
540
- /** MongoDB projection include (`1`) or exclude (`0`) fields. Typed projections deferred to v1.0. */
541
- project?: Record<string, 0 | 1>;
1015
+ type UpdateOptions = {
1016
+ /** When `true`, inserts a new document if no document matches the filter. */
1017
+ upsert?: boolean;
1018
+ };
1019
+ /**
1020
+ * Options for {@link findOneAndUpdate}.
1021
+ */
1022
+ type FindOneAndUpdateOptions = {
1023
+ /** Whether to return the document before or after the update. Defaults to `'after'`. */
1024
+ returnDocument?: 'before' | 'after';
1025
+ /** When `true`, inserts a new document if no document matches the filter. */
1026
+ upsert?: boolean;
542
1027
  /** Override the collection-level validation mode, or `false` to skip validation entirely. */
543
1028
  validate?: ValidationMode | false;
544
1029
  };
545
1030
  /**
546
- * Find a single document matching the filter.
1031
+ * Update a single document matching the filter.
547
1032
  *
548
- * Queries MongoDB, then validates the fetched document against the collection's
549
- * Zod schema. Validation mode is resolved from the per-query option, falling
550
- * back to the collection-level default (which defaults to `'strict'`).
1033
+ * Applies the update operators to the first document that matches the filter.
1034
+ * Does not validate the update against the Zod schema — validation happens
1035
+ * at the field-operator level through {@link TypedUpdateFilter}.
551
1036
  *
552
- * @param handle - The collection handle to query.
1037
+ * @param handle - The collection handle to update in.
553
1038
  * @param filter - Type-safe filter to match documents.
554
- * @param options - Optional projection and validation overrides.
555
- * @returns The matched document, or `null` if no document matches.
556
- * @throws {ZodmonValidationError} When the fetched document fails schema validation in strict mode.
1039
+ * @param update - Type-safe update operators to apply.
1040
+ * @param options - Optional settings such as `upsert`.
1041
+ * @returns The MongoDB `UpdateResult` with match/modify counts.
557
1042
  *
558
1043
  * @example
559
1044
  * ```ts
560
- * const user = await findOne(users, { name: 'Ada' })
561
- * if (user) console.log(user.role) // typed as 'admin' | 'user'
1045
+ * const result = await updateOne(users, { name: 'Ada' }, { $set: { role: 'admin' } })
1046
+ * console.log(result.modifiedCount) // 1
562
1047
  * ```
563
1048
  */
564
- declare function findOne<TDef extends AnyCollection>(handle: CollectionHandle<TDef>, filter: TypedFilter<InferDocument<TDef>>, options?: FindOneOptions): Promise<InferDocument<TDef> | null>;
1049
+ declare function updateOne<TDef extends AnyCollection>(handle: CollectionHandle<TDef>, filter: TypedFilter<InferDocument<TDef>>, update: TypedUpdateFilter<InferDocument<TDef>>, options?: UpdateOptions): Promise<UpdateResult>;
565
1050
  /**
566
- * Find a single document matching the filter, or throw if none exists.
1051
+ * Update all documents matching the filter.
567
1052
  *
568
- * Behaves identically to {@link findOne} but throws {@link ZodmonNotFoundError}
569
- * instead of returning `null` when no document matches the filter.
1053
+ * Applies the update operators to every document that matches the filter.
1054
+ * Does not validate the update against the Zod schema — validation happens
1055
+ * at the field-operator level through {@link TypedUpdateFilter}.
570
1056
  *
571
- * @param handle - The collection handle to query.
1057
+ * @param handle - The collection handle to update in.
572
1058
  * @param filter - Type-safe filter to match documents.
573
- * @param options - Optional projection and validation overrides.
574
- * @returns The matched document (never null).
575
- * @throws {ZodmonNotFoundError} When no document matches the filter.
576
- * @throws {ZodmonValidationError} When the fetched document fails schema validation in strict mode.
1059
+ * @param update - Type-safe update operators to apply.
1060
+ * @param options - Optional settings such as `upsert`.
1061
+ * @returns The MongoDB `UpdateResult` with match/modify counts.
577
1062
  *
578
1063
  * @example
579
1064
  * ```ts
580
- * const user = await findOneOrThrow(users, { name: 'Ada' })
581
- * console.log(user.role) // typed as 'admin' | 'user', guaranteed non-null
1065
+ * const result = await updateMany(users, { role: 'guest' }, { $set: { role: 'user' } })
1066
+ * console.log(result.modifiedCount) // number of guests promoted
582
1067
  * ```
583
1068
  */
584
- declare function findOneOrThrow<TDef extends AnyCollection>(handle: CollectionHandle<TDef>, filter: TypedFilter<InferDocument<TDef>>, options?: FindOneOptions): Promise<InferDocument<TDef>>;
585
- /**
586
- * Options for {@link find}.
587
- */
588
- type FindOptions = {
589
- /** Override the collection-level validation mode, or `false` to skip validation entirely. */
590
- validate?: ValidationMode | false;
591
- };
1069
+ declare function updateMany<TDef extends AnyCollection>(handle: CollectionHandle<TDef>, filter: TypedFilter<InferDocument<TDef>>, update: TypedUpdateFilter<InferDocument<TDef>>, options?: UpdateOptions): Promise<UpdateResult>;
592
1070
  /**
593
- * Find all documents matching the filter, returning a chainable typed cursor.
1071
+ * Find a single document matching the filter, apply an update, and return the document.
594
1072
  *
595
- * The cursor is lazy no query is executed until a terminal method
596
- * (`toArray`, `for await`) is called. Use `sort`, `skip`, and `limit`
597
- * to shape the query before executing.
598
- *
599
- * Each document is validated against the collection's Zod schema when
600
- * a terminal method consumes it.
1073
+ * By default, returns the document **after** the update is applied. Set
1074
+ * `returnDocument: 'before'` to get the pre-update snapshot. The returned
1075
+ * document is validated against the collection's Zod schema using the same
1076
+ * resolution logic as {@link findOne}.
601
1077
  *
602
- * @param handle - The collection handle to query.
1078
+ * @param handle - The collection handle to update in.
603
1079
  * @param filter - Type-safe filter to match documents.
604
- * @param options - Optional validation overrides.
605
- * @returns A typed cursor for chaining query modifiers.
1080
+ * @param update - Type-safe update operators to apply.
1081
+ * @param options - Optional settings: `returnDocument`, `upsert`, `validate`.
1082
+ * @returns The matched document (before or after update), or `null` if no document matches.
1083
+ * @throws {ZodmonValidationError} When the returned document fails schema validation in strict mode.
606
1084
  *
607
1085
  * @example
608
1086
  * ```ts
609
- * const admins = await find(users, { role: 'admin' })
610
- * .sort({ name: 1 })
611
- * .limit(10)
612
- * .toArray()
1087
+ * const user = await findOneAndUpdate(
1088
+ * users,
1089
+ * { name: 'Ada' },
1090
+ * { $set: { role: 'admin' } },
1091
+ * )
1092
+ * if (user) console.log(user.role) // 'admin' (returned after update)
613
1093
  * ```
614
1094
  *
615
1095
  * @example
616
1096
  * ```ts
617
- * for await (const user of find(users, {})) {
618
- * console.log(user.name)
619
- * }
1097
+ * const before = await findOneAndUpdate(
1098
+ * users,
1099
+ * { name: 'Ada' },
1100
+ * { $inc: { loginCount: 1 } },
1101
+ * { returnDocument: 'before' },
1102
+ * )
620
1103
  * ```
621
1104
  */
622
- declare function find<TDef extends AnyCollection>(handle: CollectionHandle<TDef>, filter: TypedFilter<InferDocument<TDef>>, options?: FindOptions): TypedFindCursor<TDef>;
1105
+ declare function findOneAndUpdate<TDef extends AnyCollection>(handle: CollectionHandle<TDef>, filter: TypedFilter<InferDocument<TDef>>, update: TypedUpdateFilter<InferDocument<TDef>>, options?: FindOneAndUpdateOptions): Promise<InferDocument<TDef> | null>;
623
1106
 
624
1107
  /**
625
1108
  * Typed wrapper around a MongoDB driver `Collection`.
@@ -738,6 +1221,127 @@ declare class CollectionHandle<TDef extends AnyCollection = AnyCollection> {
738
1221
  * ```
739
1222
  */
740
1223
  find(filter: TypedFilter<InferDocument<TDef>>, options?: FindOptions): TypedFindCursor<TDef>;
1224
+ /**
1225
+ * Update a single document matching the filter.
1226
+ *
1227
+ * Applies the update operators to the first document that matches the filter.
1228
+ * Does not validate the update against the Zod schema — validation happens
1229
+ * at the field-operator level through {@link TypedUpdateFilter}.
1230
+ *
1231
+ * @param filter - Type-safe filter to match documents.
1232
+ * @param update - Type-safe update operators to apply.
1233
+ * @param options - Optional settings such as `upsert`.
1234
+ * @returns The MongoDB `UpdateResult` with match/modify counts.
1235
+ *
1236
+ * @example
1237
+ * ```ts
1238
+ * const users = db.use(Users)
1239
+ * const result = await users.updateOne({ name: 'Ada' }, { $set: { role: 'admin' } })
1240
+ * console.log(result.modifiedCount) // 1
1241
+ * ```
1242
+ */
1243
+ updateOne(filter: TypedFilter<InferDocument<TDef>>, update: TypedUpdateFilter<InferDocument<TDef>>, options?: UpdateOptions): Promise<UpdateResult>;
1244
+ /**
1245
+ * Update all documents matching the filter.
1246
+ *
1247
+ * Applies the update operators to every document that matches the filter.
1248
+ * Does not validate the update against the Zod schema — validation happens
1249
+ * at the field-operator level through {@link TypedUpdateFilter}.
1250
+ *
1251
+ * @param filter - Type-safe filter to match documents.
1252
+ * @param update - Type-safe update operators to apply.
1253
+ * @param options - Optional settings such as `upsert`.
1254
+ * @returns The MongoDB `UpdateResult` with match/modify counts.
1255
+ *
1256
+ * @example
1257
+ * ```ts
1258
+ * const users = db.use(Users)
1259
+ * const result = await users.updateMany({ role: 'guest' }, { $set: { role: 'user' } })
1260
+ * console.log(result.modifiedCount) // number of guests promoted
1261
+ * ```
1262
+ */
1263
+ updateMany(filter: TypedFilter<InferDocument<TDef>>, update: TypedUpdateFilter<InferDocument<TDef>>, options?: UpdateOptions): Promise<UpdateResult>;
1264
+ /**
1265
+ * Find a single document matching the filter, apply an update, and return the document.
1266
+ *
1267
+ * By default, returns the document **after** the update is applied. Set
1268
+ * `returnDocument: 'before'` to get the pre-update snapshot. The returned
1269
+ * document is validated against the collection's Zod schema using the same
1270
+ * resolution logic as {@link findOne}.
1271
+ *
1272
+ * @param filter - Type-safe filter to match documents.
1273
+ * @param update - Type-safe update operators to apply.
1274
+ * @param options - Optional settings: `returnDocument`, `upsert`, `validate`.
1275
+ * @returns The matched document (before or after update), or `null` if no document matches.
1276
+ * @throws {ZodmonValidationError} When the returned document fails schema validation in strict mode.
1277
+ *
1278
+ * @example
1279
+ * ```ts
1280
+ * const users = db.use(Users)
1281
+ * const user = await users.findOneAndUpdate(
1282
+ * { name: 'Ada' },
1283
+ * { $set: { role: 'admin' } },
1284
+ * )
1285
+ * if (user) console.log(user.role) // 'admin' (returned after update)
1286
+ * ```
1287
+ */
1288
+ findOneAndUpdate(filter: TypedFilter<InferDocument<TDef>>, update: TypedUpdateFilter<InferDocument<TDef>>, options?: FindOneAndUpdateOptions): Promise<InferDocument<TDef> | null>;
1289
+ /**
1290
+ * Delete a single document matching the filter.
1291
+ *
1292
+ * Removes the first document that matches the filter from the collection.
1293
+ * No validation is performed — the document is deleted directly through
1294
+ * the MongoDB driver.
1295
+ *
1296
+ * @param filter - Type-safe filter to match documents.
1297
+ * @returns The MongoDB `DeleteResult` with the deleted count.
1298
+ *
1299
+ * @example
1300
+ * ```ts
1301
+ * const users = db.use(Users)
1302
+ * const result = await users.deleteOne({ name: 'Ada' })
1303
+ * console.log(result.deletedCount) // 1
1304
+ * ```
1305
+ */
1306
+ deleteOne(filter: TypedFilter<InferDocument<TDef>>): Promise<DeleteResult>;
1307
+ /**
1308
+ * Delete all documents matching the filter.
1309
+ *
1310
+ * Removes every document that matches the filter from the collection.
1311
+ * No validation is performed — documents are deleted directly through
1312
+ * the MongoDB driver.
1313
+ *
1314
+ * @param filter - Type-safe filter to match documents.
1315
+ * @returns The MongoDB `DeleteResult` with the deleted count.
1316
+ *
1317
+ * @example
1318
+ * ```ts
1319
+ * const users = db.use(Users)
1320
+ * const result = await users.deleteMany({ role: 'guest' })
1321
+ * console.log(result.deletedCount) // number of guests removed
1322
+ * ```
1323
+ */
1324
+ deleteMany(filter: TypedFilter<InferDocument<TDef>>): Promise<DeleteResult>;
1325
+ /**
1326
+ * Find a single document matching the filter, delete it, and return the document.
1327
+ *
1328
+ * Returns the deleted document, or `null` if no document matches the filter.
1329
+ * The returned document is validated against the collection's Zod schema
1330
+ * using the same resolution logic as {@link findOne}.
1331
+ *
1332
+ * @param filter - Type-safe filter to match documents.
1333
+ * @param options - Optional settings: `validate`.
1334
+ * @returns The deleted document, or `null` if no document matches.
1335
+ * @throws {ZodmonValidationError} When the returned document fails schema validation in strict mode.
1336
+ *
1337
+ * @example
1338
+ * ```ts
1339
+ * const users = db.use(Users)
1340
+ * const user = await users.findOneAndDelete({ name: 'Ada' })
1341
+ * if (user) console.log(user.name) // 'Ada' (the deleted document)
1342
+ * ```
1343
+ */
1344
+ findOneAndDelete(filter: TypedFilter<InferDocument<TDef>>, options?: FindOneAndDeleteOptions): Promise<InferDocument<TDef> | null>;
741
1345
  }
742
1346
 
743
1347
  /**
@@ -855,6 +1459,8 @@ declare function extractFieldIndexes(shape: z.core.$ZodShape): FieldIndexDefinit
855
1459
  */
856
1460
  declare function collection<TShape extends z.core.$ZodShape>(name: string, shape: TShape, options?: CollectionOptions<Extract<keyof TShape, string>>): CollectionDefinition<TShape>;
857
1461
 
1462
+ type IndexDirection = 1 | -1;
1463
+ type CompoundIndexOptions = NonNullable<CompoundIndexDefinition['options']>;
858
1464
  /**
859
1465
  * A builder for compound index definitions.
860
1466
  *
@@ -874,9 +1480,6 @@ declare function collection<TShape extends z.core.$ZodShape>(name: string, shape
874
1480
  * index({ email: 1, role: -1 }).unique().name('email_role_idx')
875
1481
  * ```
876
1482
  */
877
-
878
- type IndexDirection = 1 | -1;
879
- type CompoundIndexOptions = NonNullable<CompoundIndexDefinition['options']>;
880
1483
  declare class IndexBuilder<TKeys extends string> {
881
1484
  readonly fields: Partial<Record<TKeys, IndexDirection>>;
882
1485
  readonly options: CompoundIndexOptions;
@@ -1049,6 +1652,62 @@ declare function oid(value: ObjectId): ObjectId;
1049
1652
  */
1050
1653
  declare function isOid(value: unknown): value is ObjectId;
1051
1654
 
1655
+ /**
1656
+ * Convenience namespace that groups all query operators under a single import.
1657
+ *
1658
+ * Property names strip the `$` prefix since the namespace itself is `$`.
1659
+ * Individual operator exports (`$or`, `$gt`, etc.) remain available for
1660
+ * tree-shaking — this namespace is the ergonomic alternative.
1661
+ *
1662
+ * @example
1663
+ * ```ts
1664
+ * import { $ } from '@zodmon/core'
1665
+ *
1666
+ * users.find($.or({ role: 'admin' }, { age: $.gte(25) }))
1667
+ * users.find({ name: $.regex(/^A/i), age: $.gt(18) })
1668
+ * users.find($.and({ published: true }, { views: $.gte(100) }))
1669
+ * ```
1670
+ */
1671
+ declare const $: {
1672
+ readonly eq: <V>(value: V) => {
1673
+ $eq: V;
1674
+ };
1675
+ readonly ne: <V>(value: V) => {
1676
+ $ne: V;
1677
+ };
1678
+ readonly gt: <V>(value: V) => {
1679
+ $gt: V;
1680
+ };
1681
+ readonly gte: <V>(value: V) => {
1682
+ $gte: V;
1683
+ };
1684
+ readonly lt: <V>(value: V) => {
1685
+ $lt: V;
1686
+ };
1687
+ readonly lte: <V>(value: V) => {
1688
+ $lte: V;
1689
+ };
1690
+ readonly in: <V>(values: V[]) => {
1691
+ $in: V[];
1692
+ };
1693
+ readonly nin: <V>(values: V[]) => {
1694
+ $nin: V[];
1695
+ };
1696
+ readonly exists: (flag?: boolean) => {
1697
+ $exists: boolean;
1698
+ };
1699
+ readonly regex: (pattern: RegExp | string) => {
1700
+ $regex: RegExp | string;
1701
+ };
1702
+ readonly not: <O extends Record<string, unknown>>(op: O) => {
1703
+ $not: O;
1704
+ };
1705
+ readonly or: <T>(...filters: NoInfer<TypedFilter<T>>[]) => TypedFilter<T>;
1706
+ readonly and: <T>(...filters: NoInfer<TypedFilter<T>>[]) => TypedFilter<T>;
1707
+ readonly nor: <T>(...filters: NoInfer<TypedFilter<T>>[]) => TypedFilter<T>;
1708
+ readonly raw: <T = any>(filter: Record<string, unknown>) => TypedFilter<T>;
1709
+ };
1710
+
1052
1711
  /**
1053
1712
  * Matches values equal to the specified value.
1054
1713
  *
@@ -1189,16 +1848,14 @@ declare const $not: <O extends Record<string, unknown>>(op: O) => {
1189
1848
  *
1190
1849
  * @example
1191
1850
  * ```ts
1851
+ * // T inferred from collection's find() context
1192
1852
  * users.find($or({ role: 'admin' }, { age: $gte(18) }))
1193
1853
  *
1194
- * // Dynamic composition
1195
- * const conditions: TypedFilter<User>[] = []
1196
- * if (name) conditions.push({ name })
1197
- * if (role) conditions.push({ role })
1198
- * users.find($or(...conditions))
1854
+ * // Explicit generic for standalone usage
1855
+ * const filter = $or<User>({ role: 'admin' }, { age: $gte(18) })
1199
1856
  * ```
1200
1857
  */
1201
- declare const $or: <T>(...filters: TypedFilter<T>[]) => TypedFilter<T>;
1858
+ declare const $or: <T>(...filters: NoInfer<TypedFilter<T>>[]) => TypedFilter<T>;
1202
1859
  /**
1203
1860
  * Joins filter clauses with a logical AND. Matches documents that satisfy
1204
1861
  * all of the provided filters. Useful for dynamic filter building where
@@ -1206,6 +1863,7 @@ declare const $or: <T>(...filters: TypedFilter<T>[]) => TypedFilter<T>;
1206
1863
  *
1207
1864
  * @example
1208
1865
  * ```ts
1866
+ * // T inferred from collection's find() context
1209
1867
  * users.find($and(
1210
1868
  * $or({ role: 'admin' }, { role: 'moderator' }),
1211
1869
  * { age: $gte(18) },
@@ -1213,7 +1871,7 @@ declare const $or: <T>(...filters: TypedFilter<T>[]) => TypedFilter<T>;
1213
1871
  * ))
1214
1872
  * ```
1215
1873
  */
1216
- declare const $and: <T>(...filters: TypedFilter<T>[]) => TypedFilter<T>;
1874
+ declare const $and: <T>(...filters: NoInfer<TypedFilter<T>>[]) => TypedFilter<T>;
1217
1875
  /**
1218
1876
  * Joins filter clauses with a logical NOR. Matches documents that fail
1219
1877
  * all of the provided filters.
@@ -1224,7 +1882,7 @@ declare const $and: <T>(...filters: TypedFilter<T>[]) => TypedFilter<T>;
1224
1882
  * users.find($nor({ role: 'banned' }, { role: 'suspended' }))
1225
1883
  * ```
1226
1884
  */
1227
- declare const $nor: <T>(...filters: TypedFilter<T>[]) => TypedFilter<T>;
1885
+ declare const $nor: <T>(...filters: NoInfer<TypedFilter<T>>[]) => TypedFilter<T>;
1228
1886
  /**
1229
1887
  * Escape hatch for unsupported or raw MongoDB filter operators.
1230
1888
  * Wraps an untyped filter object so it can be passed where `TypedFilter<T>` is expected.
@@ -1314,11 +1972,70 @@ declare module 'zod' {
1314
1972
  * ```
1315
1973
  */
1316
1974
  declare function getRefMetadata(schema: unknown): RefMetadata | undefined;
1975
+
1976
+ /**
1977
+ * Shorthand for `CollectionHandle<TDef>`.
1978
+ *
1979
+ * Reduces boilerplate in function signatures that accept a collection handle.
1980
+ *
1981
+ * @example
1982
+ * ```ts
1983
+ * import { type HandleOf } from '@zodmon/core'
1984
+ *
1985
+ * const Users = collection('users', { name: z.string() })
1986
+ *
1987
+ * async function seed(users: HandleOf<typeof Users>) {
1988
+ * await users.insertOne({ name: 'Ada' })
1989
+ * }
1990
+ * ```
1991
+ */
1992
+ type HandleOf<TDef extends AnyCollection> = CollectionHandle<TDef>;
1993
+ /**
1994
+ * Shorthand for `TypedFilter<InferDocument<TDef>>`.
1995
+ *
1996
+ * Derives the filter type directly from a collection definition,
1997
+ * removing the need to compose `TypedFilter` and `InferDocument` manually.
1998
+ *
1999
+ * @example
2000
+ * ```ts
2001
+ * import { type FilterOf } from '@zodmon/core'
2002
+ *
2003
+ * const Users = collection('users', { name: z.string(), age: z.number() })
2004
+ *
2005
+ * const conditions: FilterOf<typeof Users>[] = []
2006
+ * conditions.push({ age: { $gte: 18 } })
2007
+ * ```
2008
+ */
2009
+ type FilterOf<TDef extends AnyCollection> = TypedFilter<InferDocument<TDef>>;
2010
+ /**
2011
+ * Shorthand for `TypedUpdateFilter<InferDocument<TDef>>`.
2012
+ *
2013
+ * Derives the update filter type directly from a collection definition.
2014
+ *
2015
+ * @example
2016
+ * ```ts
2017
+ * import { type UpdateFilterOf } from '@zodmon/core'
2018
+ *
2019
+ * const Users = collection('users', { name: z.string(), role: z.string() })
2020
+ *
2021
+ * const update: UpdateFilterOf<typeof Users> = { $set: { role: 'admin' } }
2022
+ * ```
2023
+ */
2024
+ type UpdateFilterOf<TDef extends AnyCollection> = TypedUpdateFilter<InferDocument<TDef>>;
1317
2025
  /**
1318
- * Install the `.ref()` extension method on `ZodType.prototype`.
2026
+ * Shorthand for `TypedSort<InferDocument<TDef>>`.
2027
+ *
2028
+ * Derives the sort specification type directly from a collection definition.
2029
+ *
2030
+ * @example
2031
+ * ```ts
2032
+ * import { type SortOf } from '@zodmon/core'
1319
2033
  *
1320
- * Idempotent safe to call multiple times.
2034
+ * const Users = collection('users', { name: z.string(), age: z.number() })
2035
+ *
2036
+ * const sort: SortOf<typeof Users> = { age: -1, name: 1 }
2037
+ * ```
1321
2038
  */
1322
- declare function installRefExtension(): void;
2039
+ type SortOf<TDef extends AnyCollection> = TypedSort<InferDocument<TDef>>;
1323
2040
 
1324
- export { $and, $eq, $exists, $gt, $gte, $in, $lt, $lte, $ne, $nin, $nor, $not, $or, $regex, type AnyCollection, type CollectionDefinition, CollectionHandle, type CollectionOptions, type ComparisonOperators, type CompoundIndexDefinition, Database, type DotPathType, type DotPaths, type FieldIndexDefinition, type FindOneOptions, type FindOptions, IndexBuilder, type IndexMetadata, type IndexOptions, type InferDocument, type InferInsert, type RefMarker, type RefMetadata, type ResolvedShape, type TypedFilter, TypedFindCursor, type TypedSort, type ValidationMode, type ZodObjectId, ZodmonNotFoundError, ZodmonValidationError, collection, createClient, extractDbName, extractFieldIndexes, find, findOne, findOneOrThrow, getIndexMetadata, getRefMetadata, index, insertMany, insertOne, installExtensions, installRefExtension, isOid, objectId, oid, raw };
2041
+ export { $, $and, $eq, $exists, $gt, $gte, $in, $lt, $lte, $ne, $nin, $nor, $not, $or, $regex, type AddToSetEach, type AddToSetFields, type AnyCollection, type ArrayElement, type CollectionDefinition, CollectionHandle, type CollectionOptions, type ComparisonOperators, type CompoundIndexDefinition, type CurrentDateFields, type CursorPage, type CursorPaginateOptions, Database, type DotPathType, type DotPaths, type FieldIndexDefinition, type FilterOf, type FindOneAndDeleteOptions, type FindOneAndUpdateOptions, type FindOneOptions, type FindOptions, type HandleOf, type IncFields, IndexBuilder, type IndexMetadata, type IndexOptions, type InferDocument, type InferInsert, type OffsetPage, type OffsetPaginateOptions, type PopFields, type PullFields, type PushFields, type PushModifiers, type RefMarker, type RefMetadata, type RenameFields, type ResolvedShape, type SetFields, type SortOf, type TypedFilter, TypedFindCursor, type TypedSort, type TypedUpdateFilter, type UnsetFields, type UpdateFilterOf, type UpdateOptions, type ValidationMode, type ZodObjectId, ZodmonNotFoundError, ZodmonValidationError, collection, createClient, deleteMany, deleteOne, extractDbName, extractFieldIndexes, find, findOne, findOneAndDelete, findOneAndUpdate, findOneOrThrow, getIndexMetadata, getRefMetadata, index, insertMany, insertOne, isOid, objectId, oid, raw, updateMany, updateOne };