2

This is the concerned part from the schema

`

var CandidateSchema = new Schema({
calculateScore:[{
jobname:{type:Schema.ObjectId,ref: 'Job'}
,Score:{type:Number,default:0}
}]
})

`

A candidate can apply to multiple jobs and get scored differently for different jobs. I want to sort the candidates depending on the specific job's Score. Any Idea?

1 Answer 1

1

Assuming the variable objectId holds the ObjectId of the referred Job, you can aggregate the records to get the records sorted by the score of that particular Job.

Since the stage operator $project does not support the $elemeMatch operation, we cannot use it to directly get the Job sub document that we want and sort based on it.

  • $project a separate field named temp_score to have a copy of the original calculateScore array.
  • $redact other sub documents from calculateScore other than whose jobname contains the id we are looking for. Now calculateScore will contain only one element in the array, i.e the element whose jobname is the id that we have specified.
  • Based on this sub document's score sort the records in descending order.
  • Once the sorting is done, project our original calculatescore field, which is in temp_score.

The code:

var objectId = ObjectId("ObjectId of the referred Job"); // Needs to be fetched 
                                                       // from the Job collection.
model.aggregate(
{$project:{"temp_score":{"level":{$literal:1},
                         "calculateScore":"$calculateScore"},
           "calculateScore":1}},
{$redact:{$cond:[
                 {$and:[
                        {$eq:[{$ifNull:["$jobname",objectId]},objectId]},
                        {$ne:["$level",1]}
                       ]
                 },
                 "$$DESCEND",
                  {$cond:[{$eq:["$level",1]},
                          "$$KEEP","$$PRUNE"]}]}},
{$sort:{"calculateScore.Score":-1}},
{$project:{"_id":1,
           "calculateScore":"$temp_score.calculateScore"}},
function(err,res)
{
    console.log(res);
}
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.