Skip to content

Commit

Permalink
docs(transactions): add example of using transactions with aggregatio…
Browse files Browse the repository at this point in the history
…n framework

Fix #6752
  • Loading branch information
vkarpov15 committed Jul 26, 2018
1 parent 729381c commit db3645d
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
11 changes: 11 additions & 0 deletions docs/transactions.jade
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,17 @@ block content
[require:transactions.*save]
```

## With the Aggregation Framework

The `Model.aggregate()` function also supports transactions. Mongoose
aggregations have a [`session()` helper](/docs/api.html#aggregate_Aggregate-session)
that sets the [`session` option](/docs/api.html#aggregate_Aggregate-option).
Below is an example of executing an aggregation within a transaction.

```javascript
[require:transactions.*aggregate]
```

block append layout
script.
_native.init("CK7DT53U", {
Expand Down
38 changes: 38 additions & 0 deletions test/docs/transactions.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,4 +97,42 @@ describe('transactions', function() {
}).
then(doc => assert.ok(doc));
});

it('aggregate', function() {
const Event = db.model('Event', new Schema({ createdAt: Date }), 'Event');

let session = null;
return db.createCollection('Event').
then(() => db.startSession()).
then(_session => {
session = _session;
session.startTransaction();
return Event.insertMany([
{ createdAt: new Date('2018-06-01') },
{ createdAt: new Date('2018-06-02') },
{ createdAt: new Date('2017-06-01') },
{ createdAt: new Date('2017-05-31') }
], { session: session });
}).
then(() => Event.aggregate([
{
$group: {
_id: {
month: { $month: '$createdAt' },
year: { $year: '$createdAt' }
},
count: { $sum: 1 }
}
},
{ $sort: { count: -1, '_id.year': -1, '_id.month': -1 } }
]).session(session)).
then(res => {
assert.deepEqual(res, [
{ _id: { month: 6, year: 2018 }, count: 2 },
{ _id: { month: 6, year: 2017 }, count: 1 },
{ _id: { month: 5, year: 2017 }, count: 1 }
]);
session.commitTransaction();
});
});
});

0 comments on commit db3645d

Please sign in to comment.