我有一个场景,在名为ratings
的数组中有评级和轮次我需要根据轮次(1,2,3,4(按降序对评分进行排序。我正在使用express js和mongoose驱动程序进行查询
查询:
**//Get top ratings based on round
exports.topRating = function(req, res) {
console.log(req.query);
Profiles.aggregate([{
$match: {
"hiringManager": req.query.hiringManager,
"ratings.round":parseInt(req.query.round)
}
},{ $sort : { "ratings.rating" : -1 } }],
function(err, profiles) {
if (err) {
return handleError(res, err);
}
console.log(profiles);
return res.status(200).json(fnStruncturedData(profiles));
});
};
架构:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var ProfilesSchema = new Schema({
name:String,
ratings: [{
round: Number,
rating: Number,
feedback: String,
interviewer: String,
roundStatus: String
}]
})
假设我有数据存储在数据库中,如下
[{
name:"a",
ratings:[{
round: 1,
rating: 3,
feedback: "something",
interviewer: "abc",
roundStatus: "selected"
},
{
round: 2,
rating: 5,
feedback: "something",
interviewer: "abc",
roundStatus: "selected"
},
{
round: 3,
rating: 4,
feedback: "something",
interviewer: "abc",
roundStatus: "selected"
},{
round: 4,
rating: 1,
feedback: "something",
interviewer: "abc",
roundStatus: "selected"
}]
},
{
name:"b",
ratings:[{
round: 1,
rating: 5,
feedback: "something",
interviewer: "abc",
roundStatus: "selected"
},
{
round: 2,
rating: 4,
feedback: "something",
interviewer: "abc",
roundStatus: "selected"
},
{
round: 3,
rating: 3,
feedback: "something",
interviewer: "abc",
roundStatus: "selected"
},{
round: 4,
rating: 2,
feedback: "something",
interviewer: "abc",
roundStatus: "selected"
}]
}]
我在客户端有一个adrop,用户可以选择轮次,相应地会出现最高评级。例如第一轮:数据被排序,根据查询,我首先得到数组中的name:b
数据第二轮:我应该先在数组中获取name:a
,但它再次首先显示name:b
数据在这里,我可以完美地对第一轮评分进行排序,而第二轮(2,3,4(没有变化我不明白这个问题出在哪里请帮助
问题是,您不感兴趣的轮次中的数据仍然包括在内,并影响您的排序阶段。
如果不需要返回其他几轮的数据,一个简单的解决方案是先解除评级,然后排除$match阶段中所有不匹配的几轮。
例如,这应该有效:
[
{
$unwind: "$ratings"
},
{
$match: {
"hiringManager": req.query.hiringManager,
"ratings.round":parseInt(req.query.round)
}
},
{
$sort: {
"ratings.rating" : -1
}
}
]