firestore-batch-updater 1.14.0 → 1.15.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/README.ko.md CHANGED
@@ -20,7 +20,7 @@
20
20
  - 비어있는지 확인 - `isEmpty()`로 매칭 문서가 없는지 확인 (`exists()`의 반대)
21
21
  - 전체 문서 조회 - `getAll()`로 매칭되는 모든 문서 데이터 조회
22
22
  - 집계 쿼리 - `aggregate()`로 서버 사이드 `sum`, `average`, `count` 연산
23
- - 간편 집계 - `sum()`과 `avg()`로 단일 필드 간편 집계
23
+ - 간편 집계 - `sum()`, `avg()`, `min()`, `max()`로 단일 필드 간편 집계
24
24
  - 커서 페이지네이션 - `paginate()`로 메모리 효율적인 페이지 단위 조회
25
25
  - ID 직접 조회 - `getOne()`으로 문서 ID로 빠른 조회
26
26
  - 벌크 작업 - `bulkCreate()`, `bulkUpdate()`, `bulkDelete()`로 여러 문서에 각기 다른 데이터로 효율적 처리
@@ -118,6 +118,8 @@ console.log(`${result.successCount}개 문서 업데이트 완료`);
118
118
  | `aggregate(spec)` | sum/average/count 집계 쿼리 | `AggregateResult` |
119
119
  | `sum(field)` | 숫자 필드 합계 조회 | `number \| null` |
120
120
  | `avg(field)` | 숫자 필드 평균 조회 | `number \| null` |
121
+ | `min(field)` | 필드 최소값 조회 | `any` |
122
+ | `max(field)` | 필드 최대값 조회 | `any` |
121
123
  | `paginate(options)` | 커서 기반 페이지네이션 | `PaginateResult` |
122
124
  | `bulkCreate(docs, options?)` | 여러 문서를 각기 다른 데이터로 생성 | `BulkCreateResult` |
123
125
  | `bulkUpdate(updates, options?)` | 여러 문서에 각기 다른 데이터 업데이트 | `BulkUpdateResult` |
@@ -542,6 +544,29 @@ console.log(`평균 점수: ${avgScore}`);
542
544
  // aggregate({ avg: { op: "average", field: "score" } }) → avg("score")
543
545
  ```
544
546
 
547
+ ### 최솟값 & 최댓값
548
+
549
+ ```typescript
550
+ // 필드의 최솟값/최댓값 조회
551
+ const cheapest = await updater.collection("products").min("price");
552
+ const mostExpensive = await updater.collection("products").max("price");
553
+ console.log(`가격 범위: ${cheapest}원 - ${mostExpensive}원`);
554
+
555
+ // 날짜/타임스탬프에도 사용 가능
556
+ const earliestOrder = await updater
557
+ .collection("orders")
558
+ .where("status", "==", "completed")
559
+ .min("createdAt");
560
+
561
+ // 매칭 문서가 없으면 null 반환
562
+ const maxScore = await updater
563
+ .collection("users")
564
+ .where("status", "==", "nonexistent")
565
+ .max("score"); // null
566
+ ```
567
+
568
+ > 참고: 한 필드에 `where()`를 걸고 다른 필드에 `min()/max()`를 사용할 경우 Firestore 복합 인덱스가 필요할 수 있습니다. `FAILED_PRECONDITION` 오류가 발생하면 오류 메시지의 링크를 통해 인덱스를 생성하세요.
569
+
545
570
  ### 커서 기반 페이지네이션
546
571
 
547
572
  ```typescript
package/README.md CHANGED
@@ -20,7 +20,7 @@ English | [한국어](./README.ko.md)
20
20
  - Empty check - Use `isEmpty()` to check if no matching documents exist (opposite of `exists()`)
21
21
  - Get all documents - Use `getAll()` to retrieve all matching documents with data
22
22
  - Aggregation - Use `aggregate()` for server-side `sum`, `average`, and `count` operations
23
- - Quick aggregation - Use `sum()` and `avg()` for simple single-field aggregation
23
+ - Quick aggregation - Use `sum()`, `avg()`, `min()`, `max()` for simple single-field aggregation
24
24
  - Cursor pagination - Use `paginate()` for memory-efficient page-by-page iteration
25
25
  - Direct ID lookup - Use `getOne()` for fast document retrieval by ID
26
26
  - Bulk operations - Use `bulkCreate()`, `bulkUpdate()`, `bulkDelete()` for efficient multi-document operations with different data each
@@ -118,6 +118,8 @@ console.log(`Updated ${result.successCount} documents`);
118
118
  | `aggregate(spec)` | Run sum/average/count queries | `AggregateResult` |
119
119
  | `sum(field)` | Get sum of a numeric field | `number \| null` |
120
120
  | `avg(field)` | Get average of a numeric field | `number \| null` |
121
+ | `min(field)` | Get minimum value of a field | `any` |
122
+ | `max(field)` | Get maximum value of a field | `any` |
121
123
  | `paginate(options)` | Cursor-based pagination | `PaginateResult` |
122
124
  | `bulkCreate(docs, options?)` | Create multiple docs with different data | `BulkCreateResult` |
123
125
  | `bulkUpdate(updates, options?)` | Update multiple docs with different data | `BulkUpdateResult` |
@@ -566,6 +568,29 @@ console.log(`Average score: ${avgScore}`);
566
568
  // aggregate({ avg: { op: "average", field: "score" } }) → avg("score")
567
569
  ```
568
570
 
571
+ ### Min & Max
572
+
573
+ ```typescript
574
+ // Get the minimum/maximum value of a field
575
+ const cheapest = await updater.collection("products").min("price");
576
+ const mostExpensive = await updater.collection("products").max("price");
577
+ console.log(`Price range: $${cheapest} - $${mostExpensive}`);
578
+
579
+ // Works with dates/timestamps too
580
+ const earliestOrder = await updater
581
+ .collection("orders")
582
+ .where("status", "==", "completed")
583
+ .min("createdAt");
584
+
585
+ // Returns null if no documents match
586
+ const maxScore = await updater
587
+ .collection("users")
588
+ .where("status", "==", "nonexistent")
589
+ .max("score"); // null
590
+ ```
591
+
592
+ > Note: Combining `where()` on one field with `min()/max()` on a different field may require a Firestore composite index. If you see a `FAILED_PRECONDITION` error, follow the link in the error message to create the required index.
593
+
569
594
  ### Cursor-Based Pagination
570
595
 
571
596
  ```typescript
package/dist/index.d.mts CHANGED
@@ -655,6 +655,20 @@ declare class BatchUpdater {
655
655
  * @returns Average of the field values, or null if no documents match
656
656
  */
657
657
  avg(field: string): Promise<number | null>;
658
+ /**
659
+ * Get the minimum value of a numeric field from matching documents
660
+ * Uses orderBy + limit(1) since Firestore doesn't support min/max aggregation natively
661
+ * @param field - Field path to find the minimum value of
662
+ * @returns Minimum field value, or null if no documents match
663
+ */
664
+ min(field: string): Promise<any>;
665
+ /**
666
+ * Get the maximum value of a numeric field from matching documents
667
+ * Uses orderBy + limit(1) since Firestore doesn't support min/max aggregation natively
668
+ * @param field - Field path to find the maximum value of
669
+ * @returns Maximum field value, or null if no documents match
670
+ */
671
+ max(field: string): Promise<any>;
658
672
  /**
659
673
  * Get documents with cursor-based pagination
660
674
  * @param options - Pagination options (pageSize, startAfter cursor)
package/dist/index.d.ts CHANGED
@@ -655,6 +655,20 @@ declare class BatchUpdater {
655
655
  * @returns Average of the field values, or null if no documents match
656
656
  */
657
657
  avg(field: string): Promise<number | null>;
658
+ /**
659
+ * Get the minimum value of a numeric field from matching documents
660
+ * Uses orderBy + limit(1) since Firestore doesn't support min/max aggregation natively
661
+ * @param field - Field path to find the minimum value of
662
+ * @returns Minimum field value, or null if no documents match
663
+ */
664
+ min(field: string): Promise<any>;
665
+ /**
666
+ * Get the maximum value of a numeric field from matching documents
667
+ * Uses orderBy + limit(1) since Firestore doesn't support min/max aggregation natively
668
+ * @param field - Field path to find the maximum value of
669
+ * @returns Maximum field value, or null if no documents match
670
+ */
671
+ max(field: string): Promise<any>;
658
672
  /**
659
673
  * Get documents with cursor-based pagination
660
674
  * @param options - Pagination options (pageSize, startAfter cursor)
package/dist/index.js CHANGED
@@ -501,6 +501,52 @@ var BatchUpdater = class {
501
501
  });
502
502
  return result._avg;
503
503
  }
504
+ /**
505
+ * Get the minimum value of a numeric field from matching documents
506
+ * Uses orderBy + limit(1) since Firestore doesn't support min/max aggregation natively
507
+ * @param field - Field path to find the minimum value of
508
+ * @returns Minimum field value, or null if no documents match
509
+ */
510
+ async min(field) {
511
+ this.validateSetup();
512
+ if (!field || typeof field !== "string") {
513
+ throw new Error("Field is required for min operation");
514
+ }
515
+ let query = this.isCollectionGroup ? this.firestore.collectionGroup(this.collectionPath) : this.firestore.collection(this.collectionPath);
516
+ for (const condition of this.conditions) {
517
+ query = query.where(condition.field, condition.operator, condition.value);
518
+ }
519
+ query = query.orderBy(field, "asc").limit(1);
520
+ const snapshot = await query.get();
521
+ if (snapshot.empty) {
522
+ return null;
523
+ }
524
+ const value = this.getNestedValue(snapshot.docs[0].data(), field);
525
+ return value ?? null;
526
+ }
527
+ /**
528
+ * Get the maximum value of a numeric field from matching documents
529
+ * Uses orderBy + limit(1) since Firestore doesn't support min/max aggregation natively
530
+ * @param field - Field path to find the maximum value of
531
+ * @returns Maximum field value, or null if no documents match
532
+ */
533
+ async max(field) {
534
+ this.validateSetup();
535
+ if (!field || typeof field !== "string") {
536
+ throw new Error("Field is required for max operation");
537
+ }
538
+ let query = this.isCollectionGroup ? this.firestore.collectionGroup(this.collectionPath) : this.firestore.collection(this.collectionPath);
539
+ for (const condition of this.conditions) {
540
+ query = query.where(condition.field, condition.operator, condition.value);
541
+ }
542
+ query = query.orderBy(field, "desc").limit(1);
543
+ const snapshot = await query.get();
544
+ if (snapshot.empty) {
545
+ return null;
546
+ }
547
+ const value = this.getNestedValue(snapshot.docs[0].data(), field);
548
+ return value ?? null;
549
+ }
504
550
  /**
505
551
  * Get documents with cursor-based pagination
506
552
  * @param options - Pagination options (pageSize, startAfter cursor)
package/dist/index.mjs CHANGED
@@ -456,6 +456,52 @@ var BatchUpdater = class {
456
456
  });
457
457
  return result._avg;
458
458
  }
459
+ /**
460
+ * Get the minimum value of a numeric field from matching documents
461
+ * Uses orderBy + limit(1) since Firestore doesn't support min/max aggregation natively
462
+ * @param field - Field path to find the minimum value of
463
+ * @returns Minimum field value, or null if no documents match
464
+ */
465
+ async min(field) {
466
+ this.validateSetup();
467
+ if (!field || typeof field !== "string") {
468
+ throw new Error("Field is required for min operation");
469
+ }
470
+ let query = this.isCollectionGroup ? this.firestore.collectionGroup(this.collectionPath) : this.firestore.collection(this.collectionPath);
471
+ for (const condition of this.conditions) {
472
+ query = query.where(condition.field, condition.operator, condition.value);
473
+ }
474
+ query = query.orderBy(field, "asc").limit(1);
475
+ const snapshot = await query.get();
476
+ if (snapshot.empty) {
477
+ return null;
478
+ }
479
+ const value = this.getNestedValue(snapshot.docs[0].data(), field);
480
+ return value ?? null;
481
+ }
482
+ /**
483
+ * Get the maximum value of a numeric field from matching documents
484
+ * Uses orderBy + limit(1) since Firestore doesn't support min/max aggregation natively
485
+ * @param field - Field path to find the maximum value of
486
+ * @returns Maximum field value, or null if no documents match
487
+ */
488
+ async max(field) {
489
+ this.validateSetup();
490
+ if (!field || typeof field !== "string") {
491
+ throw new Error("Field is required for max operation");
492
+ }
493
+ let query = this.isCollectionGroup ? this.firestore.collectionGroup(this.collectionPath) : this.firestore.collection(this.collectionPath);
494
+ for (const condition of this.conditions) {
495
+ query = query.where(condition.field, condition.operator, condition.value);
496
+ }
497
+ query = query.orderBy(field, "desc").limit(1);
498
+ const snapshot = await query.get();
499
+ if (snapshot.empty) {
500
+ return null;
501
+ }
502
+ const value = this.getNestedValue(snapshot.docs[0].data(), field);
503
+ return value ?? null;
504
+ }
459
505
  /**
460
506
  * Get documents with cursor-based pagination
461
507
  * @param options - Pagination options (pageSize, startAfter cursor)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "firestore-batch-updater",
3
- "version": "1.14.0",
3
+ "version": "1.15.0",
4
4
  "description": "Batch update Firestore documents with query-based filtering and preview",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",