2014-11-18 5 views
2

이 후보는 여러 작업에 적용 얻을 수정렬 - MongoDB를/몽구스

`

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

`

스키마에서 관련 부분입니다 각기 다른 직업에 따라 점수가 매겨집니다. 특정 직업의 점수에 따라 후보자를 분류하고 싶습니다. 어떤 아이디어? 변수 objectId 가정

답변

1

당신이 특정 Job의 점수에 의해 기록을 sorted를 얻을 수있는 기록을 집계 할 수 있으며, 언급 JobObjectId을 보유하고 있습니다.

스테이지 연산자 $project$elemeMatch 작업을 지원하지 않으므로이를 사용하여 원하는 작업 하위 문서를 직접 가져올 수 없습니다.

  • $projecttemp_score라는 별도 field

    원래 calculateScore 배열의 복사본을 가지고있다.
  • $redact 다른 하위 문서 calculateScore 이외의 사람은 jobnameid이 포함되어 있습니다. 이제 calculateScore은 배열에 요소를 하나만 포함합니다. 즉, jobnameid 인 요소입니다.
  • 이 하위 문서의 점수 sort을 기반으로 descending 의 레코드가 있습니다.
  • sorting이 완료되면 원래 calculatescore 필드를 프로젝트에 제출합니다 (temp_score).

코드 :

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