Skip to content

Commit 17616da

Browse files
author
Garret Meier
committed
feat(find): add optional hint parameter for the cursor
Adds the ability to supply an index hint to the mongo find query. This is useful for situations where there's an optimal index for a query, but mongo doesn't use it.
1 parent 23e06e0 commit 17616da

File tree

2 files changed

+23
-4
lines changed

2 files changed

+23
-4
lines changed

spec/findSpec.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -501,8 +501,26 @@ describe('find', (it) => {
501501
t.false(res.hasPrevious);
502502
});
503503

504+
it('should use a the hint parameter', async (t) => {
505+
const collection = t.context.db.collection('test_paging');
506+
await t.context.db.collection('test_paging').ensureIndex({ color: 1 }, { name: 'color_1' });
507+
// First page.
508+
const res = await paging.find(collection, {
509+
query: {
510+
color: 'blue',
511+
},
512+
hint: 'color_1',
513+
});
514+
515+
t.is(res.results.length, 5);
516+
t.is(res.results[0].color, 'blue');
517+
t.false(res.hasNext);
518+
t.false(res.hasPrevious);
519+
});
520+
504521
it('should use the "fields" parameter', async (t) => {
505522
const collection = t.context.db.collection('test_paging');
523+
506524
// First page.
507525
const res = await paging.find(collection, {
508526
query: {

src/find.js

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ const config = require('./config');
2525
* -previous {String} The value to start querying previous page.
2626
* -after {String} The _id to start querying the page.
2727
* -before {String} The _id to start querying previous page.
28+
* -hint {String} An optional index hint to provide to the mongo query
2829
*/
2930
module.exports = async function(collection, params) {
3031
const removePaginatedFieldInResponse = params.fields && !params.fields[params.paginatedField];
@@ -49,10 +50,10 @@ module.exports = async function(collection, params) {
4950
* See mongo documentation: https://docs.mongodb.com/manual/reference/collation/#collation-and-index-use
5051
*/
5152
const collatedQuery = config.COLLATION ? query.collation(config.COLLATION) : query;
52-
const results = await collatedQuery
53-
.sort($sort)
54-
.limit(params.limit + 1) // Query one more element to see if there's another page.
55-
.toArray();
53+
// Query one more element to see if there's another page.
54+
const cursor = collatedQuery.sort($sort).limit(params.limit + 1);
55+
if (params.hint) cursor.hint(params.hint);
56+
const results = await cursor.toArray();
5657

5758
const response = prepareResponse(results, params);
5859

0 commit comments

Comments
 (0)