How to increase the maximum execution timeout of aggregation

Viewed 2827

I am developing an application where I use MongoDB with Mongoose. There are some query which takes long time to give result.I know that $maxTimeMS can set maximum time for any find query but I want to set or increase query execution time for any aggregate method.How can I do that?

1 Answers

MongoDB's own node driver allows you to make the aggregate method use a cursor (it does not do this by default). When using a cursor, you can also provide it a maxTimeMS option to increase/decrease the timeout on the aggregate operation. Documented here

To do the same in Mongoose, you need to access the raw collection object for your model:

YourModel.collection.aggregate([/* pipeline */], {
  cursor: {
    batchSize: /* an appropriate batch size */
  },
  maxTimeMS: 60000
});

However, operations that run this long on MongoDB are not a good idea, so you should look into optimizing your pipeline or breaking it down. You may also want to make sure your collection is properly indexed.

Related