mongo-pipebuilder 0.2.1__tar.gz

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.
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 mongo-pipebuilder contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
@@ -0,0 +1,375 @@
1
+ Metadata-Version: 2.4
2
+ Name: mongo-pipebuilder
3
+ Version: 0.2.1
4
+ Summary: Type-safe, fluent MongoDB aggregation pipeline builder
5
+ Author-email: seligoroff <seligoroff@gmail.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/seligoroff/mongo-pipebuilder
8
+ Project-URL: Documentation, https://github.com/seligoroff/mongo-pipebuilder#readme
9
+ Project-URL: Repository, https://github.com/seligoroff/mongo-pipebuilder
10
+ Project-URL: Issues, https://github.com/seligoroff/mongo-pipebuilder/issues
11
+ Keywords: mongodb,aggregation,pipeline,builder,query
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.8
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Topic :: Database
22
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
23
+ Requires-Python: >=3.8
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: typing_extensions>=4.0.0; python_version < "3.11"
27
+ Dynamic: license-file
28
+
29
+ # mongo-pipebuilder
30
+
31
+ Type-safe, fluent MongoDB aggregation pipeline builder for Python.
32
+
33
+ ## Overview
34
+
35
+ `mongo-pipebuilder` provides a clean, type-safe way to build MongoDB aggregation pipelines using the Builder Pattern with a fluent interface for maximum readability and safety.
36
+
37
+ ## Features
38
+
39
+ - ✅ **Type-safe**: Full type hints support with IDE autocomplete
40
+ - ✅ **Fluent interface**: Chain methods for readable, maintainable code
41
+ - ✅ **Zero dependencies**: Pure Python, lightweight package
42
+ - ✅ **Extensible**: Easy to add custom stages via `add_stage()`
43
+ - ✅ **Well tested**: Comprehensive test suite with 96%+ coverage
44
+
45
+ ## Installation
46
+
47
+ ```bash
48
+ pip install mongo-pipebuilder
49
+ ```
50
+
51
+ ## Quick Start
52
+
53
+ ```python
54
+ from mongo_pipebuilder import PipelineBuilder
55
+
56
+ # Build a pipeline
57
+ pipeline = (
58
+ PipelineBuilder()
59
+ .match({"status": "active"})
60
+ .lookup(
61
+ from_collection="users",
62
+ local_field="userId",
63
+ foreign_field="_id",
64
+ as_field="user"
65
+ )
66
+ .project({"name": 1, "user.email": 1})
67
+ .sort({"name": 1})
68
+ .limit(10)
69
+ .build()
70
+ )
71
+
72
+ # Use with pymongo
73
+ from pymongo import MongoClient
74
+ client = MongoClient()
75
+ collection = client.db.my_collection
76
+ results = collection.aggregate(pipeline)
77
+ ```
78
+
79
+ ## API Reference
80
+
81
+ ### PipelineBuilder
82
+
83
+ Main class for building aggregation pipelines.
84
+
85
+ #### Methods
86
+
87
+ ##### `match(conditions: Dict[str, Any]) -> Self`
88
+
89
+ Adds a `$match` stage to filter documents.
90
+
91
+ ```python
92
+ .match({"status": "active", "age": {"$gte": 18}})
93
+ ```
94
+
95
+ ##### `lookup(from_collection: str, local_field: str, foreign_field: str, as_field: str, pipeline: Optional[List[Dict[str, Any]]] = None) -> Self`
96
+
97
+ Adds a `$lookup` stage to join with another collection.
98
+
99
+ ```python
100
+ .lookup(
101
+ from_collection="users",
102
+ local_field="userId",
103
+ foreign_field="_id",
104
+ as_field="user",
105
+ pipeline=[{"$match": {"active": True}}] # Optional nested pipeline
106
+ )
107
+ ```
108
+
109
+ ##### `add_fields(fields: Dict[str, Any]) -> Self`
110
+
111
+ Adds a `$addFields` stage to add or modify fields.
112
+
113
+ ```python
114
+ .add_fields({"fullName": {"$concat": ["$firstName", " ", "$lastName"]}})
115
+ ```
116
+
117
+ ##### `project(fields: Dict[str, Any]) -> Self`
118
+
119
+ Adds a `$project` stage to reshape documents.
120
+
121
+ ```python
122
+ .project({"name": 1, "email": 1, "_id": 0})
123
+ ```
124
+
125
+ ##### `group(group_by: Dict[str, Any], accumulators: Dict[str, Any]) -> Self`
126
+
127
+ Adds a `$group` stage to group documents.
128
+
129
+ ```python
130
+ .group(
131
+ group_by={"category": "$category"},
132
+ accumulators={"total": {"$sum": "$amount"}}
133
+ )
134
+ ```
135
+
136
+ ##### `unwind(path: str, preserve_null_and_empty_arrays: bool = False, include_array_index: Optional[str] = None) -> Self`
137
+
138
+ Adds a `$unwind` stage to deconstruct arrays.
139
+
140
+ ```python
141
+ .unwind("tags", preserve_null_and_empty_arrays=True)
142
+ .unwind("items", include_array_index="itemIndex")
143
+ ```
144
+
145
+ ##### `sort(fields: Dict[str, int]) -> Self`
146
+
147
+ Adds a `$sort` stage.
148
+
149
+ ```python
150
+ .sort({"createdAt": -1, "name": 1})
151
+ ```
152
+
153
+ ##### `limit(limit: int) -> Self`
154
+
155
+ Adds a `$limit` stage.
156
+
157
+ ```python
158
+ .limit(10)
159
+ ```
160
+
161
+ ##### `skip(skip: int) -> Self`
162
+
163
+ Adds a `$skip` stage.
164
+
165
+ ```python
166
+ .skip(20)
167
+ ```
168
+
169
+ ##### `unset(fields: Union[str, List[str]]) -> Self`
170
+
171
+ Adds a `$unset` stage to remove fields from documents.
172
+
173
+ ```python
174
+ .unset("temp_field")
175
+ .unset(["field1", "field2", "field3"])
176
+ ```
177
+
178
+ ##### `replace_root(new_root: Dict[str, Any]) -> Self`
179
+
180
+ Adds a `$replaceRoot` stage to replace the root document.
181
+
182
+ ```python
183
+ .replace_root({"newRoot": "$embedded"})
184
+ .replace_root({"newRoot": {"$mergeObjects": ["$doc1", "$doc2"]}})
185
+ ```
186
+
187
+ ##### `replace_with(replacement: Any) -> Self`
188
+
189
+ Adds a `$replaceWith` stage (alias for `$replaceRoot` in MongoDB 4.2+).
190
+
191
+ ```python
192
+ .replace_with("$embedded")
193
+ .replace_with({"$mergeObjects": ["$doc1", "$doc2"]})
194
+ ```
195
+
196
+ ##### `facet(facets: Dict[str, List[Dict[str, Any]]]) -> Self`
197
+
198
+ Adds a `$facet` stage for parallel execution of multiple sub-pipelines.
199
+
200
+ ```python
201
+ .facet({
202
+ "items": [{"$skip": 10}, {"$limit": 20}],
203
+ "meta": [{"$count": "total"}]
204
+ })
205
+ ```
206
+
207
+ ##### `count(field_name: str = "count") -> Self`
208
+
209
+ Adds a `$count` stage to count documents.
210
+
211
+ ```python
212
+ .match({"status": "active"}).count("active_count")
213
+ ```
214
+
215
+ ##### `set_field(fields: Dict[str, Any]) -> Self`
216
+
217
+ Adds a `$set` stage (alias for `$addFields` in MongoDB 3.4+).
218
+
219
+ ```python
220
+ .set_field({"status": "active", "updatedAt": "$$NOW"})
221
+ ```
222
+
223
+ ##### `add_stage(stage: Dict[str, Any]) -> Self`
224
+
225
+ Adds a custom stage for advanced use cases.
226
+
227
+ ```python
228
+ .add_stage({"$facet": {
229
+ "categories": [{"$group": {"_id": "$category"}}],
230
+ "total": [{"$count": "count"}]
231
+ }})
232
+ ```
233
+
234
+ ##### `prepend(stage: Dict[str, Any]) -> Self`
235
+
236
+ Adds a stage at the beginning of the pipeline.
237
+
238
+ ```python
239
+ builder.match({"status": "active"})
240
+ builder.prepend({"$match": {"deleted": False}})
241
+ # Pipeline: [{"$match": {"deleted": False}}, {"$match": {"status": "active"}}]
242
+ ```
243
+
244
+ ##### `insert_at(position: int, stage: Dict[str, Any]) -> Self`
245
+
246
+ Inserts a stage at a specific position (0-based index) in the pipeline.
247
+
248
+ ```python
249
+ builder.match({"status": "active"}).group({"_id": "$category"}, {"count": {"$sum": 1}})
250
+ builder.insert_at(1, {"$sort": {"name": 1}})
251
+ # Pipeline: [{"$match": {...}}, {"$sort": {...}}, {"$group": {...}}]
252
+ ```
253
+
254
+ **Note:** For inserting before a specific stage type, combine with `get_stage_types()`:
255
+
256
+ ```python
257
+ stage_types = builder.get_stage_types()
258
+ group_index = stage_types.index("$group")
259
+ builder.insert_at(group_index, {"$addFields": {"x": 1}})
260
+ ```
261
+
262
+ ##### `validate() -> bool`
263
+
264
+ Validates the pipeline before execution. Checks that:
265
+ - Pipeline is not empty
266
+ - `$out` and `$merge` stages are the last stages (critical MongoDB rule)
267
+ - `$out` and `$merge` are not used together
268
+
269
+ ```python
270
+ builder = PipelineBuilder()
271
+ builder.match({"status": "active"}).validate() # Returns True
272
+
273
+ # Invalid: $out not last
274
+ builder.add_stage({"$out": "output"}).match({"status": "active"})
275
+ builder.validate() # Raises ValueError: $out stage must be the last stage
276
+ ```
277
+
278
+ ##### `build() -> List[Dict[str, Any]]`
279
+
280
+ Returns the complete pipeline as a list of stage dictionaries.
281
+
282
+ ## Examples
283
+
284
+ ### Complex Pipeline with Nested Lookup
285
+
286
+ ```python
287
+ pipeline = (
288
+ PipelineBuilder()
289
+ .match({"status": "published"})
290
+ .lookup(
291
+ from_collection="authors",
292
+ local_field="authorId",
293
+ foreign_field="_id",
294
+ as_field="author"
295
+ )
296
+ .unwind("author", preserve_null_and_empty_arrays=True)
297
+ .lookup(
298
+ from_collection="categories",
299
+ local_field="categoryId",
300
+ foreign_field="_id",
301
+ as_field="category",
302
+ pipeline=[
303
+ {"$match": {"active": True}},
304
+ {"$project": {"name": 1, "slug": 1}}
305
+ ]
306
+ )
307
+ .unwind("category")
308
+ .add_fields({
309
+ "authorName": "$author.name",
310
+ "categoryName": "$category.name"
311
+ })
312
+ .project({
313
+ "title": 1,
314
+ "authorName": 1,
315
+ "categoryName": 1,
316
+ "publishedAt": 1
317
+ })
318
+ .sort({"publishedAt": -1})
319
+ .limit(20)
320
+ .build()
321
+ )
322
+ ```
323
+
324
+ ### Aggregation with Grouping
325
+
326
+ ```python
327
+ pipeline = (
328
+ PipelineBuilder()
329
+ .match({"date": {"$gte": "2024-01-01"}})
330
+ .group(
331
+ group_by={"month": {"$dateToString": {"format": "%Y-%m", "date": "$date"}}},
332
+ accumulators={
333
+ "totalSales": {"$sum": "$amount"},
334
+ "avgAmount": {"$avg": "$amount"},
335
+ "count": {"$sum": 1}
336
+ }
337
+ )
338
+ .sort({"month": 1})
339
+ .build()
340
+ )
341
+ ```
342
+
343
+ ## Development
344
+
345
+ ### Project Structure
346
+
347
+ ```
348
+ mongo-pipebuilder/
349
+ ├── src/
350
+ │ └── mongo_pipebuilder/
351
+ │ ├── __init__.py
352
+ │ └── builder.py
353
+ ├── tests/
354
+ │ └── test_builder.py
355
+ ├── examples/
356
+ │ └── examples.py
357
+ ├── pyproject.toml
358
+ ├── README.md
359
+ └── LICENSE
360
+ ```
361
+
362
+ ### Running Tests
363
+
364
+ ```bash
365
+ pytest tests/
366
+ ```
367
+
368
+ ### Contributing
369
+
370
+ See [DEVELOPMENT.md](DEVELOPMENT.md) for development guidelines.
371
+
372
+ ## License
373
+
374
+ MIT License - see [LICENSE](LICENSE) file for details.
375
+