Open benthayer opened 4 months ago
Mongoose's insertMany()
won't exactly match the throughput of the MongoDB node driver because of defaults, casting, validation, etc. We'll see how we can improve the performance, but you can always use the lean
option to bypass Mongoose's casting, validation, etc. using await Collection.insertMany(documents, { lean: true });
Prerequisites
Last performant version
unknown
Slowed down in version
8.4.3
Node.js version
20.9.0
🦥 Performance issue
We have a high throughput application where our performance is limited by the number of db writes. During our testing we found mongoose's insertMany to be extremely slow compared to the insertMany provided by the mongodb package.
We were able to achieve a maximum throughput of 1900 documents written per second on a single unindexed collection by using batches of 50 documents per insertMany, with 1000 concurrent insertmany calls and minPoolSize set to 1000.
With the mongodb package, we were able to achieve 58,000 writes per second by using a similar concurrency of 1000 and 200 documents per insertMany call. This means that for this part of our application we have to bypass mongoose and use the underlying mongodb api.
Using Collection.create, we were able to achieve only a maximum of 650 documents inserted per second.
Steps to Reproduce
This is the code I was using for testing. You'd have to replace the uri with your uri obviously.
With the same settings, mongoose performs worse. If we recreate and use our production collection (with 50+ fields of varying types) we get significantly lower throughput for mongooes but we're still able to get higher throughput for native insertManys. Additionally, if I set batchSize to be too high for mongoose, I get an out of memory error which may indicate something about what's causing the performance issue (or not?). I got the error by using
await benchmarkBulkInsert(writeMongoose, 1000, 1000);
Expected Behavior
I would expect the throughput of mongoose's insertMany to exactly match the throughput of the native mongodb insertMany.