Skip to content

perf(NODE-5906): optimize toArray to use batches #4171

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 12 commits into from
Aug 7, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion src/cursor/abstract_cursor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,7 @@ export abstract class AbstractCursor<

return bufferedDocs;
}

async *[Symbol.asyncIterator](): AsyncGenerator<TSchema, void, void> {
if (this.isClosed) {
return;
Expand Down Expand Up @@ -457,9 +458,24 @@ export abstract class AbstractCursor<
* cursor.rewind() can be used to reset the cursor.
*/
async toArray(): Promise<TSchema[]> {
const array = [];
const array: TSchema[] = [];

// when each loop iteration ends,documents will be empty and a 'await (const document of this)' will run a getMore operation
for await (const document of this) {
array.push(document);
let docs = this.readBufferedDocuments();
if (this.transform != null) {
docs = await Promise.all(
docs.map(async doc => {
if (doc != null) {
return await this.transformDocument(doc);
} else {
throw Error;
}
})
);
}
array.push(...docs);
}
return array;
}
Expand Down
34 changes: 34 additions & 0 deletions test/integration/node-specific/abstract_cursor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Transform } from 'stream';
import { inspect } from 'util';

import {
AbstractCursor,
type Collection,
type FindCursor,
MongoAPIError,
Expand Down Expand Up @@ -361,4 +362,37 @@ describe('class AbstractCursor', function () {
});
});
});

describe('toArray', () => {
let nextSpy;
let client: MongoClient;
let cursor: AbstractCursor;
let col: Collection;
const numBatches = 10;
const batchSize = 4;

beforeEach(async function () {
client = this.configuration.newClient();
col = client.db().collection('test');
await col.deleteMany({});
for (let i = 0; i < numBatches; i++) {
await col.insertMany([{ a: 1 }, { a: 2 }, { a: 3 }, { a: 4 }]);
}
nextSpy = sinon.spy(AbstractCursor.prototype, 'next');
});

afterEach(async function () {
sinon.restore();
await cursor.close();
await client.close();
});

it('iterates per batch not per document', async () => {
cursor = client.db().collection('test').find({}, { batchSize });
await cursor.toArray();
expect(nextSpy.callCount).to.equal(numBatches + 1);
const numDocuments = numBatches * batchSize;
expect(nextSpy.callCount).to.be.lessThan(numDocuments);
});
});
});