@@ -51,6 +51,7 @@ block content
51
51
<li><a href="#connection-string-options">Connection String Options</a></li>
52
52
<li><a href="#refs">References to other documents</a></li>
53
53
<li><a href="#streaming">Streaming</a></li>
54
+ <li><a href="#versus-aggregation">Versus Aggregation</a></li>
54
55
</ul>
55
56
56
57
### Executing
@@ -176,6 +177,48 @@ block content
176
177
});
177
178
```
178
179
180
+ <h3 id="versus-aggregation"><a href="#versus-aggregation">Versus Aggregation</a></h3>
181
+
182
+ [Aggregation](https://mongoosejs.com/docs/api.html#aggregate_Aggregate) can
183
+ do many of the same things that queries can. For example, below is
184
+ how you can use `aggregate()` to find docs where `name.last = 'Ghost'`:
185
+
186
+ ```javascript
187
+ const docs = await Person.aggregate([{ $match: { 'name.last': 'Ghost' } }]);
188
+ ```
189
+
190
+ However, just because you can use `aggregate()` doesn't mean you should.
191
+ In general, you should use queries where possible, and only use `aggregate()`
192
+ when you absolutely need to.
193
+
194
+ Unlike query results, Mongoose does **not** [`hydrate()`](/docs/api/model.html#model_Model.hydrate)
195
+ aggregation results. Aggregation results are always POJOs, not Mongoose
196
+ documents.
197
+
198
+ ```javascript
199
+ const docs = await Person.aggregate([{ $match: { 'name.last': 'Ghost' } }]);
200
+
201
+ docs[0] instanceof mongoose.Document; // false
202
+ ```
203
+
204
+ Also, unlike query filters, Mongoose also doesn't
205
+ [cast](/docs/tutorials/query_casting.html) aggregation pipelines. That means
206
+ you're responsible for ensuring the values you pass in to an aggregation
207
+ pipeline have the correct type.
208
+
209
+ ```javascript
210
+ const doc = await Person.findOne();
211
+
212
+ const idString = doc._id.toString();
213
+
214
+ // Finds the `Person`, because Mongoose casts `idString` to an ObjectId
215
+ const queryRes = await Person.findOne({ _id: idString });
216
+
217
+ // Does **not** find the `Person`, because Mongoose doesn't cast aggregation
218
+ // pipelines.
219
+ const aggRes = await Person.aggregate([{ $match: { _id: idString } }])
220
+ ```
221
+
179
222
<h3 id="next"><a href="#next">Next Up</a></h3>
180
223
181
224
Now that we've covered `Queries`, let's take a look at [Validation](/docs/validation.html).
0 commit comments