@@ -85,9 +85,17 @@ export class MongoDBQueue<T = any> {
8585
8686 public async createIndexes ( ) : Promise < void > {
8787 await Promise . all ( [
88- this . col . createIndex ( { deleted : 1 , visible : 1 } ) ,
88+ this . col . createIndex ( { visible : 1 } , { sparse : true } ) ,
8989 this . col . createIndex ( { ack : 1 } , { unique : true , sparse : true } ) ,
9090 this . col . createIndex ( { deleted : 1 } , { sparse : true } ) ,
91+
92+ // Index for efficient counts on in-flight
93+ this . col . createIndex ( { visible : 1 , ack : 1 } , {
94+ partialFilterExpression : {
95+ visible : { $exists : true } ,
96+ ack : { $exists : true } ,
97+ } ,
98+ } ) ,
9199 ] ) ;
92100 }
93101
@@ -121,7 +129,6 @@ export class MongoDBQueue<T = any> {
121129 public async get ( opts : GetOptions = { } ) : Promise < ExternalMessage < T > | null > {
122130 const visibility = opts . visibility || this . visibility ;
123131 const query : Filter < Partial < Message < T > > > = {
124- deleted : { $exists : false } ,
125132 visible : { $lte : now ( ) } ,
126133 } ;
127134 const sort : Sort = {
@@ -172,7 +179,6 @@ export class MongoDBQueue<T = any> {
172179 const query : Filter < Partial < Message < T > > > = {
173180 ack : ack ,
174181 visible : { $gt : now ( ) } ,
175- deleted : { $exists : false } ,
176182 } ;
177183 const update : UpdateFilter < Message < T > > = {
178184 $set : {
@@ -202,7 +208,6 @@ export class MongoDBQueue<T = any> {
202208 const query : Filter < Partial < Message < T > > > = {
203209 ack : ack ,
204210 visible : { $gt : now ( ) } ,
205- deleted : { $exists : false } ,
206211 } ;
207212 const update : UpdateFilter < Message < T > > = {
208213 $set : {
@@ -237,16 +242,17 @@ export class MongoDBQueue<T = any> {
237242
238243 public async size ( ) : Promise < number > {
239244 return this . col . countDocuments ( {
240- deleted : { $exists : false } ,
241245 visible : { $lte : now ( ) } ,
242246 } ) ;
243247 }
244248
245249 public async inFlight ( ) : Promise < number > {
246250 return this . col . countDocuments ( {
247- ack : { $exists : true } ,
251+ // For some unknown reason, MongoDB refuses to use the partial index with
252+ // {$exists: true}, but *will* use it if we use {$gt: ''}
253+ // https://www.mongodb.com/community/forums/t/partial-index-is-not-used-during-search/290507/2
254+ ack : { $gt : '' } ,
248255 visible : { $gt : now ( ) } ,
249- deleted : { $exists : false } ,
250256 } ) ;
251257 }
252258
0 commit comments