我目前正在尝试为MongoDB中的每个项目文档添加价格。其中许多价格都有范围,例如Item A的价格范围是$50至$100。我该如何在数据库中存储这些范围并根据这些值进行查询?我考虑给每个文档添加两个属性,即lowPrice和highPrice,分别用于保存项目价格范围的最低价和最高价。然后,在查询时,我只需查询lowPrice小于或等于查询价格且highPrice大于或等于查询价格的文档。但我觉得可能有更有效的方法来处理这个问题。如果有任何建议,请告诉我!
你提出的最低价和最高价的解决方案很好。
看一下这里的Mongo查询比较。
db.test.find({
minNum : { $gte : 50},
maxNum : { $lte : 100}
});
https://docs.mongodb.com/manual/reference/operator/query-comparison/
price: { $lte: maxPrice || 1000000000, $gte: minPrice || 0 }
如果maxPrice为空,则默认值为1亿。
如果minPrice为空,则默认值为0。
这个答案与问题不太相关,但是对于正在寻找类似条件的人可能会有帮助。
db.testCollection.find({
lowVal : {$gte : 50},
highVal : {$lte : 100}
});
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
});
});
};