【问题标题】:How to use mongodb aggregate in this case?在这种情况下如何使用 mongodb 聚合?
【发布时间】:2021-01-02 10:39:22
【问题描述】:

有什么方法可以让这个 mongoose 查询更小更快地用于生产?

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 })

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    对于每个类别,您可以尝试将 $push 运算符与 $cond 运算符结合使用,以仅推送符合您的条件的元素,如下例所示:

    Mongodb - aggregation $push if conditional

    你必须在 $group 阶段这样做

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

    【讨论】:

      猜你喜欢
      • 2021-11-15
      • 2013-05-16
      • 1970-01-01
      • 2021-05-25
      • 2022-11-02
      • 2022-01-23
      • 2015-11-30
      • 2017-05-16
      • 2012-10-06
      相关资源
      最近更新 更多