Mongoose, How to limit the query based on the sum of a field in the document

Viewed 99

I have a document in the shape of

const Model = mongoose.Schema({
  something1: {type:String},
  someNumber1:{type:Number},
  something2: {type:String},
  someNumber2:{type:Number},
  aFloatNumber: {type:Number}
)}

and after indexing the document like

Model.index({something1:1 , something2:1 , aFloatNumber:1})

for better performance which I hope I am doing right and please correct me if I am doing it wrong.

I am trying to query usign syntax:

const model = await Model.find({
  $and:[{something1:anInput}, {something2:anotherInput}]})
  .sort(aFloatNumber)

now I want to limit the returned query as it could be a very large list to improve performance, however, this limit changes based on an input. Basically I want the mongoose to keep adding someNumber1 together and stop returning after it gets larger than the input number. Something like the code bellow:

const model = await Model.find({
          $and:[{something1:anInput}, {something2:anotherInput}]})
          .sort(aFloatNumber)
          .limit( sum(someNumber1) >= theInputNumber )

So basically my questions are:

  1. Am I indexing the document correctly based on my query?
  2. Does it make any difference on the performance to limit the query since it is sorting the data and I think it is going to check all the document to be able to sort it?
  3. If it makes a huge difference on the performance, what is the correct syntax for it as I am going to make this query a lot in my application?
1 Answers
Related