如何在Mongoose中进行范围查询?

6
我目前正在尝试为MongoDB中的每个项目文档添加价格。其中许多价格都有范围,例如Item A的价格范围是$50至$100。我该如何在数据库中存储这些范围并根据这些值进行查询?我考虑给每个文档添加两个属性,即lowPrice和highPrice,分别用于保存项目价格范围的最低价和最高价。然后,在查询时,我只需查询lowPrice小于或等于查询价格且highPrice大于或等于查询价格的文档。但我觉得可能有更有效的方法来处理这个问题。如果有任何建议,请告诉我!
4个回答

4

3
如果您在价格范围内查询(最高价和最低价),那么如果用户没有提供最高价或最低价,或者用户未提供任何价格,该怎么办?
        price: { $lte: maxPrice || 1000000000, $gte: minPrice || 0 }
  • 如果maxPrice为空,则默认值为1亿。

  • 如果minPrice为空,则默认值为0。

这个答案与问题不太相关,但是对于正在寻找类似条件的人可能会有帮助。


1
db.testCollection.find({
       lowVal : {$gte : 50},
       highVal : {$lte : 100}
});

感谢您解释答案,以使其对读者有价值。 - Webwoman

1
exports.listBySearch = (req, res) => {
    let order = req.body.order ? req.body.order : 'desc';
    let sortBy = req.body.sortBy ? req.body.sortBy : '_id';
    let limit = req.body.limit ? parseInt(req.body.limit) : 100;
    let skip = parseInt(req.body.skip);
    let findArgs = {};

    // console.log(order, sortBy, limit, skip, req.body.filters);
    // console.log("findArgs", findArgs);

    for (let key in req.body.filters) {
        if (req.body.filters[key].length > 0) {
            if (key === 'price') {
                // gte -  greater than price [0-10]
                // lte - less than
                findArgs[key] = {
                    $gte: req.body.filters[key][0],
                    $lte: req.body.filters[key][1]
                };
            } else {
                findArgs[key] = req.body.filters[key];
            }
        }
    }

    Product.find(findArgs)
        .select('-photo')
        .populate('category')
        .sort([[sortBy, order]])
        .skip(skip)
        .limit(limit)
        .exec((err, data) => {
            if (err) {
                return res.status(400).json({
                    error: 'Products not found'
                });
            }
            res.json({
                size: data.length,
                data
            });
        });
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接