Pipeline API¶
Pipeline
¶
MongoDB aggregation pipeline builder.
This class acts as a container for aggregation stages and can be directly passed to MongoDB's aggregate() method. It implements iter to allow MongoDB drivers to iterate through the stages.
Example
pipeline = Pipeline() pipeline.add_stage(Match(field="status", value="active")) pipeline.add_stage(Group(id="$category", count={"$sum": 1})) collection.aggregate(pipeline)
Or with constructor¶
pipeline = Pipeline([ ... Match(field="status", value="active"), ... Unwind(path="items") ... ])
Source code in mongo_aggro/base.py
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 | |
__init__
¶
Initialize the pipeline with optional initial stages.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stages
|
list[BaseStage] | None
|
Optional list of initial pipeline stages |
None
|
add_stage
¶
Append a new stage to the pipeline.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stage
|
BaseStage
|
A pipeline stage instance |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Self |
Self
|
Self for method chaining |
to_list
¶
Convert the entire pipeline to a list of dictionaries.
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
list[dict[str, Any]]: List of MongoDB stage dictionaries |
__len__
¶
__iter__
¶
Iterate through pipeline stages as dictionaries.
This allows the pipeline to be directly passed to MongoDB's aggregate() method without calling any additional methods.
Yields:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: Each stage's MongoDB dictionary representation |