Skip to content

Commit

Permalink
feat: add support for aggregation hints
Browse files Browse the repository at this point in the history
This module supports `hint`s for `find` queries, and this commit adds logic to
support `hint`s for `aggregation`s.
  • Loading branch information
Srinand Balaji committed Aug 26, 2021
1 parent 1e89f97 commit b90acd4
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/aggregate.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ const config = require('./config');
* -previous {String} The value to start querying previous page.
* -after {String} The _id to start querying the page.
* -before {String} The _id to start querying previous page.
* -options {Object} Aggregation options
*/
module.exports = async function aggregate(collection, params) {
params = _.defaults(await sanitizeParams(collection, params), { aggregation: [] });
Expand All @@ -57,6 +58,10 @@ module.exports = async function aggregate(collection, params) {
params.aggregation.splice(index + 1, 0, { $sort });
params.aggregation.splice(index + 2, 0, { $limit: params.limit + 1 });

// Aggregation options:
// https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#aggregate
// https://mongodb.github.io/node-mongodb-native/4.0/interfaces/aggregateoptions.html
const options = params.options || {};
/**
* IMPORTANT
*
Expand All @@ -66,7 +71,7 @@ module.exports = async function aggregate(collection, params) {
*
* See mongo documentation: https://docs.mongodb.com/manual/reference/collation/#collation-and-index-use
*/
const options = config.COLLATION ? { collation: config.COLLATION } : undefined;
if (config.COLLATION) options.collation = config.COLLATION;

// Support both the native 'mongodb' driver and 'mongoist'. See:
// https://www.npmjs.com/package/mongoist#cursor-operations
Expand Down
37 changes: 37 additions & 0 deletions test/aggregate.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,14 @@ describe('aggregate', () => {
name: 'saturn',
},
]),
t.db.collection('test_aggregation_lookup').ensureIndex(
{
name: 'text',
},
{
name: 'test_index',
}
),
t.db.collection('test_aggregation_sort').insert([
{
name: 'Alpha',
Expand Down Expand Up @@ -668,4 +676,33 @@ describe('aggregate', () => {
]);
});
});

describe('aggregation options', () => {
let spy;
beforeEach(() => {
spy = jest.spyOn(paging, 'aggregate');
});

afterEach(() => {
spy.mockRestore();
});

it('invokes aggregate with a `hint` if one is passed in via params object', async () => {
const collection = t.db.collection('test_aggregation_lookup');

await paging.aggregate(collection, {
aggregation: [
{
$sort: { name: 1 },
},
],
hint: 'test_index',
});

expect(spy).toHaveBeenCalledWith(
expect.any(Object),
expect.objectContaining({ hint: 'test_index' })
);
});
});
});

0 comments on commit b90acd4

Please sign in to comment.