2017-09-10 4 views
0

competitions.length보다 큰 모든 문서를 find으로 보내고 싶습니다.개체 배열 내의 배열 크기를 비교하십시오.

{ 
    "_id" : ObjectId("59b28f432b4353d3f311dd1b"), 
    "name" : "Ford Focus RS 2008", 
    "requirements" : [ 
     { 
      "rankType" : "D1", 
      "competitions" : [ 
       ObjectId("59b151fd2b4353d3f3116827"), 
       ObjectId("59b151fd2b4353d3f3116829") 
      ], 
      "sCompetitions" : [ 
       "Rallye Monte-Carlo", 
       "Rally Sweden" 
      ] 
     }, 
     { 
      "rankType" : "A3", 
      "competitions" : [ 
       ObjectId("59b151fd2b4353d3f3116f6b") 
      ], 
      "sCompetitions" : [ 
       "Rally Italia Sardegna", 
       "Neste Rally Finland" 
      ] 
     } 
    ] 
}, 
{ 
    "_id" : ObjectId("0000b28f432b4353f311dd1b"), 
    "name" : "Ford Focus RS 2012", 
    "requirements" : [ 
     { 
      "rankType" : "D1", 
      "competitions" : [ 
       ObjectId("59b151fd2b4353d3f3116827"), 
       ObjectId("59b151fd2b4353d3f3116829") 
      ], 
      "sCompetitions" : [ 
       "Rallye Monte-Carlo", 
       "Rally Sweden" 
      ] 
     }, 
     { 
      "rankType" : "A3", 
      "competitions" : [ 
       ObjectId("59b151fd2b4353d3f3116f6b"), 
       ObjectId("59b151fd2b4353d3f3116f6b") 
      ], 
      "sCompetitions" : [ 
       "Rally Italia Sardegna", 
       "Neste Rally Finland" 
      ] 
     } 
    ] 
} 

그래서 샘플을보고 단지 ObjectId("59b28f432b4353d3f311dd1b")

내 문제가 requirements은 그 자체로 배열 인 것을, 그래서 어떻게 든 그것을 반복 할 필요가 반환 : 여기

는 일부 샘플 문서 문서의

답변

1

"반복"할 필요가 없습니다. $map에서 결과를 반환 한 후 실제로 필요한 것은 $anyElementTrue 수표입니다.

Model.aggregate([ 
    { "$redact": { 
    "$cond": { 
     "if": { 
     "$anyElementTrue": { 
      "$map": { 
      "input": "$requirements", 
      "as": "r", 
      "in": { 
       "$gt": [ 
       { "$size": "$$r.sCompetitions" }, 
       { "$size": "$$r.competitions" } 
       ] 
      } 
      } 
     } 
     }, 
     "then": "$$KEEP", 
     "else": "$$PRUNE" 
    } 
    }} 
]) 

그래서 각 배열 요소에 대한 $size에 의해 단순 비교가, 그리고 그 다른 요소의 "어떤이"true이다 문서는 "유지"또는 그렇지 않은 경우 : 그리고 당신은 모든 $redact 액션 내에서이 작업을 수행 할 수 있습니다 결과에서 "정리"합니다.

+0

감사합니다. 호기심에서'in '연산자를 사용할 수 있습니까? 예 : 'sCompetitions.length'가'competitions.length'보다 큰 모든 문서를 찾고 싶다면 * OR *'rankType == 'CC'' – Cornwell

+0

@Cornwell 원하는대로 사용할 수 있습니다. 여기서 각 배열 요소에 대해 부울을 반환하는 유일한 포인트입니다. 이것은 당신이 요청한 조건이기 때문에 ['$ gt'] (https://docs.mongodb.com/manual/reference/operator/aggregation/gt/)을 사용합니다. 그러나 [비교 연산자] (https://docs.mongodb.com/manual/reference/operator/aggregation-comparison/) 또는 참으로 부울을 반환하는 다양한 다른 연산자를 동일한 목적으로 사용할 수 있습니다. –