Skip to content

Commit 5b2b0e5

Browse files
committed
docs(queries): clarify when to use queries versus aggregations
Fix #8494
1 parent d62e141 commit 5b2b0e5

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

docs/queries.pug

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ block content
5151
<li><a href="#connection-string-options">Connection String Options</a></li>
5252
<li><a href="#refs">References to other documents</a></li>
5353
<li><a href="#streaming">Streaming</a></li>
54+
<li><a href="#versus-aggregation">Versus Aggregation</a></li>
5455
</ul>
5556

5657
### Executing
@@ -176,6 +177,48 @@ block content
176177
});
177178
```
178179

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+
179222
<h3 id="next"><a href="#next">Next Up</a></h3>
180223

181224
Now that we've covered `Queries`, let's take a look at [Validation](/docs/validation.html).

0 commit comments

Comments
 (0)