I have a pretty large Mongo collection which I want to query in batches of 50K docs using a cursor with a pre-defined batchSize.
This is my code-
const aggregation = [{ $match: { example: '1' }}]
await mongoose.connect(CONNECTION_STRING)
const db = mongoose.connection
db.collection('some-collection')
.aggregate(aggregation)
.cursor({ batchSize: 50000 })
.exec()
await cursor.eachAsync(async (doc) => {
// do something
})
For some reason I keep getting the following error –
TypeError: db.collection(...).aggregate(...).cursor is not a function
What am I doing wrong? Is there any other way to query Mongo in batches?
2
Answers
AFAIK there is no
.cursor()
function. You should specify batch size in theoptions
parametr of.aggregate()
.None of the answers here worked for me (using Mongoose 6.3 on a ver 5.x MongoDB server) in 2022. According to their latest documentation this is what you have to do, and you don’t need to chain
.exec()
onto it anymore: