0

Is there any way I can make this mongoose query smaller and faster for production?

const currentYear = (new Date).getFullYear()
const usedCars = await CarModel.find({ ModelYear: {$lte: currentYear - 1} }).limit(10)
const recentCars = await CarModel.find({ ModelYear: currentYear }).limit(10)
const sedanType = await CarModel.find({ BodyType: 'Sedan' }).limit(10)
const hatchbackType = await CarModel.find({ BodyType: 'Hatchback' }).limit(10)
const suvType = await CarModel.find({ BodyType: 'SUV' }).limit(10)
const under5K = await CarModel.find({ Price: {$lte: 5000} }).limit(10)
const under10K = await CarModel.find({ Price: {$gt: 5000, $lte: 10000} }).limit(10)
const above10K = await CarModel.find({ Price: {$gt: 10000} }).limit(10)


res.send({ usedCars, recentCars, sedanType, hatchbackType, suvType, under5K, under10K, above10K })
Bhupen Pal
  • 31
  • 4

1 Answers1

0

For each category you can try to use the $push operator combined with the $cond operator to push only the elements that fit your criteria like in this example :

Mongodb - aggregation $push if conditional

You must do so inside the $group stage

https://docs.mongodb.com/manual/reference/operator/aggregation/group/

clanglai
  • 149
  • 1
  • 6