2017-09-10 12 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" 
      ] 
     } 
    ] 
} 

だから私の問題はrequirements自体が配列であるので、私は何とかそれを反復する必要があるだろうということです、それは唯一のObjectId("59b28f432b4353d3f311dd1b")

を返すサンプルを見ているが、

答えて

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 'の中で'OR'演算子を使うことはできますか?例えば。 '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/)または真にブール値を返す他のさまざまなものを同じ目的で使用することができます。 –