firestore-batch-updater 1.16.0 → 1.18.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
@@ -21,6 +21,7 @@
21
21
  - 전체 문서 조회 - `getAll()`로 매칭되는 모든 문서 데이터 조회
22
22
  - 집계 쿼리 - `aggregate()`로 서버 사이드 `sum`, `average`, `count` 연산
23
23
  - 간편 집계 - `sum()`, `avg()`, `min()`, `max()`로 단일 필드 간편 집계
24
+ - 통합 통계 - `fieldStats()`로 sum/avg/min/max/count 한 번에 조회
24
25
  - 커서 페이지네이션 - `paginate()`로 메모리 효율적인 페이지 단위 조회
25
26
  - ID 직접 조회 - `getOne()`으로 문서 ID로 빠른 조회
26
27
  - 벌크 작업 - `bulkCreate()`, `bulkUpdate()`, `bulkDelete()`로 여러 문서에 각기 다른 데이터로 효율적 처리
@@ -29,6 +30,7 @@
29
30
  - 고유값 조회 - `distinct()`로 특정 필드의 중복 없는 값 목록 조회
30
31
  - JSON 내보내기/가져오기 - `toJSON()` / `fromJSON()`으로 문서 JSON 파일 내보내기/가져오기
31
32
  - 그룹별 개수 조회 - `countBy()`로 특정 필드 값별 문서 수 집계
33
+ - 그룹별 문서 조회 - `groupBy()`로 필드 값별로 문서 그룹핑
32
34
  - 랜덤 샘플링 - `sample()`로 쿼리 결과에서 랜덤 문서 추출
33
35
  - 필드 값 추출 - `pluck()`로 특정 필드 값만 간단하게 배열로 추출
34
36
  - 문서 ID 추출 - `pluckIds()`로 매칭 문서의 ID만 배열로 추출
@@ -121,6 +123,7 @@ console.log(`${result.successCount}개 문서 업데이트 완료`);
121
123
  | `avg(field)` | 숫자 필드 평균 조회 | `number \| null` |
122
124
  | `min(field)` | 필드 최소값 조회 | `any` |
123
125
  | `max(field)` | 필드 최대값 조회 | `any` |
126
+ | `fieldStats(field)` | sum/avg/min/max/count 한 번에 조회 | `FieldStatsResult` |
124
127
  | `paginate(options)` | 커서 기반 페이지네이션 | `PaginateResult` |
125
128
  | `bulkCreate(docs, options?)` | 여러 문서를 각기 다른 데이터로 생성 | `BulkCreateResult` |
126
129
  | `bulkUpdate(updates, options?)` | 여러 문서에 각기 다른 데이터 업데이트 | `BulkUpdateResult` |
@@ -134,6 +137,7 @@ console.log(`${result.successCount}개 문서 업데이트 완료`);
134
137
  | `toJSON(path, options?)` | 문서를 JSON 파일로 내보내기 | `ToJSONResult` |
135
138
  | `fromJSON(path, options?)` | JSON 파일에서 문서 가져오기 | `FromJSONResult` |
136
139
  | `countBy(field)` | 필드 값별 문서 수 집계 | `CountByResult` |
140
+ | `groupBy(field)` | 필드 값별 문서 그룹핑 | `GroupByResult` |
137
141
  | `getFields(field)` | 특정 필드 값 조회 | `FieldValueResult[]` |
138
142
 
139
143
  ### 옵션
@@ -182,6 +186,7 @@ console.log(`${result.successCount}개 문서 업데이트 완료`);
182
186
  | `UpsertResult` | `successCount`, `failureCount`, `totalCount`, `failedDocIds?`, `logFilePath?` |
183
187
  | `DeleteResult` | `successCount`, `failureCount`, `totalCount`, `deletedIds[]`, `failedDocIds?`, `logFilePath?` |
184
188
  | `AggregateResult` | `{ [alias]: number \| null }` |
189
+ | `FieldStatsResult` | `sum`, `avg`, `min`, `max`, `count` |
185
190
  | `PaginateResult` | `docs[]`, `nextCursor`, `hasMore` |
186
191
  | `BulkCreateResult` | `successCount`, `failureCount`, `totalCount`, `createdIds[]`, `failedDocIds?`, `logFilePath?` |
187
192
  | `BulkUpdateResult` | `successCount`, `failureCount`, `totalCount`, `failedDocIds?`, `logFilePath?` |
@@ -191,6 +196,7 @@ console.log(`${result.successCount}개 문서 업데이트 완료`);
191
196
  | `ToJSONResult` | `filePath`, `documentCount` |
192
197
  | `FromJSONResult` | `successCount`, `failureCount`, `totalCount`, `createdIds[]`, `failedDocIds?`, `logFilePath?` |
193
198
  | `CountByResult` | `{ [value]: number }` |
199
+ | `GroupByResult` | `{ [value]: { id, data }[] }` |
194
200
  | `FieldValueResult` | `id`, `value` |
195
201
 
196
202
  ## 사용 예시
@@ -569,6 +575,26 @@ const maxScore = await updater
569
575
 
570
576
  > 참고: 한 필드에 `where()`를 걸고 다른 필드에 `min()/max()`를 사용할 경우 Firestore 복합 인덱스가 필요할 수 있습니다. `FAILED_PRECONDITION` 오류가 발생하면 오류 메시지의 링크를 통해 인덱스를 생성하세요.
571
577
 
578
+ ### 통합 필드 통계
579
+
580
+ ```typescript
581
+ // 한 필드의 sum, avg, min, max, count를 한 번에 조회
582
+ const stats = await updater.collection("products").fieldStats("price");
583
+ console.log(stats);
584
+ // { sum: 12500, avg: 250, min: 50, max: 500, count: 50 }
585
+
586
+ // 대시보드에서 유용
587
+ const orderStats = await updater
588
+ .collection("orders")
589
+ .where("status", "==", "completed")
590
+ .fieldStats("amount");
591
+
592
+ console.log(`총 매출: ${orderStats.sum}원`);
593
+ console.log(`평균 주문액: ${orderStats.avg}원`);
594
+ console.log(`주문 수: ${orderStats.count}건`);
595
+ console.log(`범위: ${orderStats.min}원 - ${orderStats.max}원`);
596
+ ```
597
+
572
598
  ### 커서 기반 페이지네이션
573
599
 
574
600
  ```typescript
@@ -789,6 +815,33 @@ const countryCounts = await updater.collection("users").countBy("address.country
789
815
  console.log(countryCounts); // { US: 80, KR: 45, JP: 25 }
790
816
  ```
791
817
 
818
+ ### 필드 값별 문서 그룹핑
819
+
820
+ ```typescript
821
+ // 필드 값별로 문서를 그룹핑 (전체 문서 데이터 포함)
822
+ const usersByRole = await updater.collection("users").groupBy("role");
823
+
824
+ console.log(`관리자: ${usersByRole.admin.length}명`);
825
+ usersByRole.admin.forEach(user => {
826
+ console.log(`- ${user.id}: ${user.data.name}`);
827
+ });
828
+
829
+ // where 필터와 함께 사용
830
+ const activeProducts = await updater
831
+ .collection("products")
832
+ .where("status", "==", "active")
833
+ .groupBy("category");
834
+
835
+ for (const [category, products] of Object.entries(activeProducts)) {
836
+ console.log(`${category}: ${products.length}개`);
837
+ }
838
+
839
+ // 중첩 필드 지원
840
+ const usersByCountry = await updater
841
+ .collection("users")
842
+ .groupBy("address.country");
843
+ ```
844
+
792
845
  ### JSON 가져오기
793
846
 
794
847
  ```typescript
package/README.md CHANGED
@@ -21,6 +21,7 @@ English | [한국어](./README.ko.md)
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
23
  - Quick aggregation - Use `sum()`, `avg()`, `min()`, `max()` for simple single-field aggregation
24
+ - Combined stats - Use `fieldStats()` to get sum/avg/min/max/count in one call
24
25
  - Cursor pagination - Use `paginate()` for memory-efficient page-by-page iteration
25
26
  - Direct ID lookup - Use `getOne()` for fast document retrieval by ID
26
27
  - Bulk operations - Use `bulkCreate()`, `bulkUpdate()`, `bulkDelete()` for efficient multi-document operations with different data each
@@ -29,6 +30,7 @@ English | [한국어](./README.ko.md)
29
30
  - Distinct values - Use `distinct()` to get unique field values from matching documents
30
31
  - JSON export/import - Use `toJSON()` / `fromJSON()` to export/import documents as JSON
31
32
  - Group counting - Use `countBy()` to count documents grouped by field value
33
+ - Group documents - Use `groupBy()` to group matching documents by a field value
32
34
  - Random sampling - Use `sample()` to get random documents from query results
33
35
  - Field value extraction - Use `pluck()` to get a simple array of field values
34
36
  - Document ID extraction - Use `pluckIds()` to get an array of matching document IDs
@@ -121,6 +123,7 @@ console.log(`Updated ${result.successCount} documents`);
121
123
  | `avg(field)` | Get average of a numeric field | `number \| null` |
122
124
  | `min(field)` | Get minimum value of a field | `any` |
123
125
  | `max(field)` | Get maximum value of a field | `any` |
126
+ | `fieldStats(field)` | Get sum/avg/min/max/count for a field in one call | `FieldStatsResult` |
124
127
  | `paginate(options)` | Cursor-based pagination | `PaginateResult` |
125
128
  | `bulkCreate(docs, options?)` | Create multiple docs with different data | `BulkCreateResult` |
126
129
  | `bulkUpdate(updates, options?)` | Update multiple docs with different data | `BulkUpdateResult` |
@@ -134,6 +137,7 @@ console.log(`Updated ${result.successCount} documents`);
134
137
  | `toJSON(path, options?)` | Export documents to JSON file | `ToJSONResult` |
135
138
  | `fromJSON(path, options?)` | Import documents from JSON file | `FromJSONResult` |
136
139
  | `countBy(field)` | Count documents grouped by field value | `CountByResult` |
140
+ | `groupBy(field)` | Group documents by field value | `GroupByResult` |
137
141
  | `getFields(field)` | Get specific field values | `FieldValueResult[]` |
138
142
 
139
143
  ### Options
@@ -182,6 +186,7 @@ All write operations support an optional `options` parameter:
182
186
  | `UpsertResult` | `successCount`, `failureCount`, `totalCount`, `failedDocIds?`, `logFilePath?` |
183
187
  | `DeleteResult` | `successCount`, `failureCount`, `totalCount`, `deletedIds[]`, `failedDocIds?`, `logFilePath?` |
184
188
  | `AggregateResult` | `{ [alias]: number \| null }` |
189
+ | `FieldStatsResult` | `sum`, `avg`, `min`, `max`, `count` |
185
190
  | `PaginateResult` | `docs[]`, `nextCursor`, `hasMore` |
186
191
  | `BulkCreateResult` | `successCount`, `failureCount`, `totalCount`, `createdIds[]`, `failedDocIds?`, `logFilePath?` |
187
192
  | `BulkUpdateResult` | `successCount`, `failureCount`, `totalCount`, `failedDocIds?`, `logFilePath?` |
@@ -191,6 +196,7 @@ All write operations support an optional `options` parameter:
191
196
  | `ToJSONResult` | `filePath`, `documentCount` |
192
197
  | `FromJSONResult` | `successCount`, `failureCount`, `totalCount`, `createdIds[]`, `failedDocIds?`, `logFilePath?` |
193
198
  | `CountByResult` | `{ [value]: number }` |
199
+ | `GroupByResult` | `{ [value]: { id, data }[] }` |
194
200
  | `FieldValueResult` | `id`, `value` |
195
201
 
196
202
  ## Usage Examples
@@ -593,6 +599,26 @@ const maxScore = await updater
593
599
 
594
600
  > 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.
595
601
 
602
+ ### Combined Field Stats
603
+
604
+ ```typescript
605
+ // Get sum, avg, min, max, count for a single field in one call
606
+ const stats = await updater.collection("products").fieldStats("price");
607
+ console.log(stats);
608
+ // { sum: 12500, avg: 250, min: 50, max: 500, count: 50 }
609
+
610
+ // Useful for dashboards
611
+ const orderStats = await updater
612
+ .collection("orders")
613
+ .where("status", "==", "completed")
614
+ .fieldStats("amount");
615
+
616
+ console.log(`Total revenue: $${orderStats.sum}`);
617
+ console.log(`Average order: $${orderStats.avg}`);
618
+ console.log(`Order count: ${orderStats.count}`);
619
+ console.log(`Range: $${orderStats.min} - $${orderStats.max}`);
620
+ ```
621
+
596
622
  ### Cursor-Based Pagination
597
623
 
598
624
  ```typescript
@@ -802,6 +828,33 @@ const countryCounts = await updater.collection("users").countBy("address.country
802
828
  console.log(countryCounts); // { US: 80, KR: 45, JP: 25 }
803
829
  ```
804
830
 
831
+ ### Group Documents by Field Value
832
+
833
+ ```typescript
834
+ // Group documents by a field value (with full document data)
835
+ const usersByRole = await updater.collection("users").groupBy("role");
836
+
837
+ console.log(`Admins: ${usersByRole.admin.length}`);
838
+ usersByRole.admin.forEach(user => {
839
+ console.log(`- ${user.id}: ${user.data.name}`);
840
+ });
841
+
842
+ // With where filter
843
+ const activeProducts = await updater
844
+ .collection("products")
845
+ .where("status", "==", "active")
846
+ .groupBy("category");
847
+
848
+ for (const [category, products] of Object.entries(activeProducts)) {
849
+ console.log(`${category}: ${products.length} products`);
850
+ }
851
+
852
+ // Nested field support
853
+ const usersByCountry = await updater
854
+ .collection("users")
855
+ .groupBy("address.country");
856
+ ```
857
+
805
858
  ### Import from JSON
806
859
 
807
860
  ```typescript
package/dist/index.d.mts CHANGED
@@ -455,12 +455,33 @@ interface CopyToResult {
455
455
  copiedIds: string[];
456
456
  failedDocIds?: string[];
457
457
  }
458
+ /**
459
+ * Result of fieldStats operation
460
+ * Combined statistics for a single field
461
+ */
462
+ interface FieldStatsResult {
463
+ sum: number | null;
464
+ avg: number | null;
465
+ min: any;
466
+ max: any;
467
+ count: number;
468
+ }
458
469
  /**
459
470
  * Result of countBy operation
460
471
  */
461
472
  interface CountByResult {
462
473
  [value: string]: number;
463
474
  }
475
+ /**
476
+ * Result of groupBy operation
477
+ * Field value → array of matching documents
478
+ */
479
+ interface GroupByResult {
480
+ [value: string]: {
481
+ id: string;
482
+ data: Record<string, any>;
483
+ }[];
484
+ }
464
485
  /**
465
486
  * Options for fromJSON operation
466
487
  */
@@ -669,6 +690,13 @@ declare class BatchUpdater {
669
690
  * @returns Maximum field value, or null if no documents match
670
691
  */
671
692
  max(field: string): Promise<any>;
693
+ /**
694
+ * Get combined statistics (sum, avg, min, max, count) for a single field
695
+ * Convenience method that runs aggregate + min + max in parallel
696
+ * @param field - Field path to compute statistics for
697
+ * @returns Object with sum, avg, min, max, count
698
+ */
699
+ fieldStats(field: string): Promise<FieldStatsResult>;
672
700
  /**
673
701
  * Get documents with cursor-based pagination
674
702
  * @param options - Pagination options (pageSize, startAfter cursor)
@@ -793,6 +821,12 @@ declare class BatchUpdater {
793
821
  * @returns Object mapping field values to their document counts
794
822
  */
795
823
  countBy(field: string): Promise<CountByResult>;
824
+ /**
825
+ * Group matching documents by a specific field value
826
+ * @param field - Field path to group by
827
+ * @returns Object mapping field values to arrays of matching documents { id, data }
828
+ */
829
+ groupBy(field: string): Promise<GroupByResult>;
796
830
  /**
797
831
  * Import documents from a JSON file into Firestore
798
832
  * @param filePath - Path to the JSON file to import
@@ -897,4 +931,4 @@ declare function isValidUpdateData(value: any): value is Record<string, any>;
897
931
  */
898
932
  declare function formatError(error: unknown, context?: string): string;
899
933
 
900
- export { type AggregateResult, type AggregateSpec, BatchUpdater, type BulkCreateInput, type BulkCreateOptions, type BulkCreateResult, type BulkDeleteOptions, type BulkDeleteResult, type BulkUpdateInput, type BulkUpdateOptions, type BulkUpdateResult, type CopyToOptions, type CopyToResult, type CountByResult, type CountResult, type CreateDocumentInput, type CreateOneResult, type CreateOptions, type CreateResult, type DeleteOptions, type DeleteResult, type DocumentSnapshot, type DryRunResult, type FieldValueResult, type FromJSONOptions, type FromJSONResult, type LogEntry, type LogOptions, type OperationLog, type OrderByCondition, type PaginateOptions, type PaginateResult, type PreviewResult, type ProgressInfo, type ToJSONOptions, type ToJSONResult, type TransformFn, type TransformOptions, type TransformResult, type UpdateOptions, type UpdateResult, type UpsertOptions, type UpsertResult, type WhereCondition, calculateProgress, createLogCollector, formatError, formatOperationLog, getAffectedFields, isValidUpdateData, mergeUpdateData, writeOperationLog };
934
+ export { type AggregateResult, type AggregateSpec, BatchUpdater, type BulkCreateInput, type BulkCreateOptions, type BulkCreateResult, type BulkDeleteOptions, type BulkDeleteResult, type BulkUpdateInput, type BulkUpdateOptions, type BulkUpdateResult, type CopyToOptions, type CopyToResult, type CountByResult, type CountResult, type CreateDocumentInput, type CreateOneResult, type CreateOptions, type CreateResult, type DeleteOptions, type DeleteResult, type DocumentSnapshot, type DryRunResult, type FieldStatsResult, type FieldValueResult, type FromJSONOptions, type FromJSONResult, type GroupByResult, type LogEntry, type LogOptions, type OperationLog, type OrderByCondition, type PaginateOptions, type PaginateResult, type PreviewResult, type ProgressInfo, type ToJSONOptions, type ToJSONResult, type TransformFn, type TransformOptions, type TransformResult, type UpdateOptions, type UpdateResult, type UpsertOptions, type UpsertResult, type WhereCondition, calculateProgress, createLogCollector, formatError, formatOperationLog, getAffectedFields, isValidUpdateData, mergeUpdateData, writeOperationLog };
package/dist/index.d.ts CHANGED
@@ -455,12 +455,33 @@ interface CopyToResult {
455
455
  copiedIds: string[];
456
456
  failedDocIds?: string[];
457
457
  }
458
+ /**
459
+ * Result of fieldStats operation
460
+ * Combined statistics for a single field
461
+ */
462
+ interface FieldStatsResult {
463
+ sum: number | null;
464
+ avg: number | null;
465
+ min: any;
466
+ max: any;
467
+ count: number;
468
+ }
458
469
  /**
459
470
  * Result of countBy operation
460
471
  */
461
472
  interface CountByResult {
462
473
  [value: string]: number;
463
474
  }
475
+ /**
476
+ * Result of groupBy operation
477
+ * Field value → array of matching documents
478
+ */
479
+ interface GroupByResult {
480
+ [value: string]: {
481
+ id: string;
482
+ data: Record<string, any>;
483
+ }[];
484
+ }
464
485
  /**
465
486
  * Options for fromJSON operation
466
487
  */
@@ -669,6 +690,13 @@ declare class BatchUpdater {
669
690
  * @returns Maximum field value, or null if no documents match
670
691
  */
671
692
  max(field: string): Promise<any>;
693
+ /**
694
+ * Get combined statistics (sum, avg, min, max, count) for a single field
695
+ * Convenience method that runs aggregate + min + max in parallel
696
+ * @param field - Field path to compute statistics for
697
+ * @returns Object with sum, avg, min, max, count
698
+ */
699
+ fieldStats(field: string): Promise<FieldStatsResult>;
672
700
  /**
673
701
  * Get documents with cursor-based pagination
674
702
  * @param options - Pagination options (pageSize, startAfter cursor)
@@ -793,6 +821,12 @@ declare class BatchUpdater {
793
821
  * @returns Object mapping field values to their document counts
794
822
  */
795
823
  countBy(field: string): Promise<CountByResult>;
824
+ /**
825
+ * Group matching documents by a specific field value
826
+ * @param field - Field path to group by
827
+ * @returns Object mapping field values to arrays of matching documents { id, data }
828
+ */
829
+ groupBy(field: string): Promise<GroupByResult>;
796
830
  /**
797
831
  * Import documents from a JSON file into Firestore
798
832
  * @param filePath - Path to the JSON file to import
@@ -897,4 +931,4 @@ declare function isValidUpdateData(value: any): value is Record<string, any>;
897
931
  */
898
932
  declare function formatError(error: unknown, context?: string): string;
899
933
 
900
- export { type AggregateResult, type AggregateSpec, BatchUpdater, type BulkCreateInput, type BulkCreateOptions, type BulkCreateResult, type BulkDeleteOptions, type BulkDeleteResult, type BulkUpdateInput, type BulkUpdateOptions, type BulkUpdateResult, type CopyToOptions, type CopyToResult, type CountByResult, type CountResult, type CreateDocumentInput, type CreateOneResult, type CreateOptions, type CreateResult, type DeleteOptions, type DeleteResult, type DocumentSnapshot, type DryRunResult, type FieldValueResult, type FromJSONOptions, type FromJSONResult, type LogEntry, type LogOptions, type OperationLog, type OrderByCondition, type PaginateOptions, type PaginateResult, type PreviewResult, type ProgressInfo, type ToJSONOptions, type ToJSONResult, type TransformFn, type TransformOptions, type TransformResult, type UpdateOptions, type UpdateResult, type UpsertOptions, type UpsertResult, type WhereCondition, calculateProgress, createLogCollector, formatError, formatOperationLog, getAffectedFields, isValidUpdateData, mergeUpdateData, writeOperationLog };
934
+ export { type AggregateResult, type AggregateSpec, BatchUpdater, type BulkCreateInput, type BulkCreateOptions, type BulkCreateResult, type BulkDeleteOptions, type BulkDeleteResult, type BulkUpdateInput, type BulkUpdateOptions, type BulkUpdateResult, type CopyToOptions, type CopyToResult, type CountByResult, type CountResult, type CreateDocumentInput, type CreateOneResult, type CreateOptions, type CreateResult, type DeleteOptions, type DeleteResult, type DocumentSnapshot, type DryRunResult, type FieldStatsResult, type FieldValueResult, type FromJSONOptions, type FromJSONResult, type GroupByResult, type LogEntry, type LogOptions, type OperationLog, type OrderByCondition, type PaginateOptions, type PaginateResult, type PreviewResult, type ProgressInfo, type ToJSONOptions, type ToJSONResult, type TransformFn, type TransformOptions, type TransformResult, type UpdateOptions, type UpdateResult, type UpsertOptions, type UpsertResult, type WhereCondition, calculateProgress, createLogCollector, formatError, formatOperationLog, getAffectedFields, isValidUpdateData, mergeUpdateData, writeOperationLog };
package/dist/index.js CHANGED
@@ -547,6 +547,34 @@ var BatchUpdater = class {
547
547
  const value = this.getNestedValue(snapshot.docs[0].data(), field);
548
548
  return value ?? null;
549
549
  }
550
+ /**
551
+ * Get combined statistics (sum, avg, min, max, count) for a single field
552
+ * Convenience method that runs aggregate + min + max in parallel
553
+ * @param field - Field path to compute statistics for
554
+ * @returns Object with sum, avg, min, max, count
555
+ */
556
+ async fieldStats(field) {
557
+ this.validateSetup();
558
+ if (!field || typeof field !== "string") {
559
+ throw new Error("Field is required for fieldStats operation");
560
+ }
561
+ const [aggResult, minVal, maxVal] = await Promise.all([
562
+ this.aggregate({
563
+ _sum: { op: "sum", field },
564
+ _avg: { op: "average", field },
565
+ _count: { op: "count" }
566
+ }),
567
+ this.min(field),
568
+ this.max(field)
569
+ ]);
570
+ return {
571
+ sum: aggResult._sum,
572
+ avg: aggResult._avg,
573
+ min: minVal,
574
+ max: maxVal,
575
+ count: aggResult._count ?? 0
576
+ };
577
+ }
550
578
  /**
551
579
  * Get documents with cursor-based pagination
552
580
  * @param options - Pagination options (pageSize, startAfter cursor)
@@ -1422,6 +1450,31 @@ var BatchUpdater = class {
1422
1450
  }
1423
1451
  return counts;
1424
1452
  }
1453
+ /**
1454
+ * Group matching documents by a specific field value
1455
+ * @param field - Field path to group by
1456
+ * @returns Object mapping field values to arrays of matching documents { id, data }
1457
+ */
1458
+ async groupBy(field) {
1459
+ this.validateSetup();
1460
+ if (!field || typeof field !== "string") {
1461
+ throw new Error("Field path is required");
1462
+ }
1463
+ const query = this.buildQuery();
1464
+ const snapshot = await query.get();
1465
+ const groups = {};
1466
+ for (const doc of snapshot.docs) {
1467
+ const data = doc.data();
1468
+ const value = this.getNestedValue(data, field);
1469
+ if (value === void 0 || value === null) continue;
1470
+ const key = String(value);
1471
+ if (!groups[key]) {
1472
+ groups[key] = [];
1473
+ }
1474
+ groups[key].push({ id: doc.id, data });
1475
+ }
1476
+ return groups;
1477
+ }
1425
1478
  /**
1426
1479
  * Import documents from a JSON file into Firestore
1427
1480
  * @param filePath - Path to the JSON file to import
package/dist/index.mjs CHANGED
@@ -502,6 +502,34 @@ var BatchUpdater = class {
502
502
  const value = this.getNestedValue(snapshot.docs[0].data(), field);
503
503
  return value ?? null;
504
504
  }
505
+ /**
506
+ * Get combined statistics (sum, avg, min, max, count) for a single field
507
+ * Convenience method that runs aggregate + min + max in parallel
508
+ * @param field - Field path to compute statistics for
509
+ * @returns Object with sum, avg, min, max, count
510
+ */
511
+ async fieldStats(field) {
512
+ this.validateSetup();
513
+ if (!field || typeof field !== "string") {
514
+ throw new Error("Field is required for fieldStats operation");
515
+ }
516
+ const [aggResult, minVal, maxVal] = await Promise.all([
517
+ this.aggregate({
518
+ _sum: { op: "sum", field },
519
+ _avg: { op: "average", field },
520
+ _count: { op: "count" }
521
+ }),
522
+ this.min(field),
523
+ this.max(field)
524
+ ]);
525
+ return {
526
+ sum: aggResult._sum,
527
+ avg: aggResult._avg,
528
+ min: minVal,
529
+ max: maxVal,
530
+ count: aggResult._count ?? 0
531
+ };
532
+ }
505
533
  /**
506
534
  * Get documents with cursor-based pagination
507
535
  * @param options - Pagination options (pageSize, startAfter cursor)
@@ -1377,6 +1405,31 @@ var BatchUpdater = class {
1377
1405
  }
1378
1406
  return counts;
1379
1407
  }
1408
+ /**
1409
+ * Group matching documents by a specific field value
1410
+ * @param field - Field path to group by
1411
+ * @returns Object mapping field values to arrays of matching documents { id, data }
1412
+ */
1413
+ async groupBy(field) {
1414
+ this.validateSetup();
1415
+ if (!field || typeof field !== "string") {
1416
+ throw new Error("Field path is required");
1417
+ }
1418
+ const query = this.buildQuery();
1419
+ const snapshot = await query.get();
1420
+ const groups = {};
1421
+ for (const doc of snapshot.docs) {
1422
+ const data = doc.data();
1423
+ const value = this.getNestedValue(data, field);
1424
+ if (value === void 0 || value === null) continue;
1425
+ const key = String(value);
1426
+ if (!groups[key]) {
1427
+ groups[key] = [];
1428
+ }
1429
+ groups[key].push({ id: doc.id, data });
1430
+ }
1431
+ return groups;
1432
+ }
1380
1433
  /**
1381
1434
  * Import documents from a JSON file into Firestore
1382
1435
  * @param filePath - Path to the JSON file to import
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "firestore-batch-updater",
3
- "version": "1.16.0",
3
+ "version": "1.18.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",