2017-01-24 12 views
2
で検索

はのは、私がテストと呼ばれるコレクションを持っているとしましょう:配列要素の比較

> db.test.find() 
{ "_id" : ObjectId("5887a9202d599801b7df2c3c"), "name" : "soccer66", "ratings" : [ 5, 3.2, 1 ] } 
{ "_id" : ObjectId("5887a9232d599801b7df2c3d"), "name" : "user1", "ratings" : [ 2, 3.2, 1 ] } 
{ "_id" : ObjectId("5887a9262d599801b7df2c3e"), "name" : "user2", "ratings" : [ 2.5, 4.9, 1 ] } 

最初の評価は二以上であるドキュメントを選択するための最適な方法は何ですか?私はたくさんの質問を試みました。

> db.test.aggregate([ 
     {$project:{"isGreater":{$cond:[{$gt:["$ratings.0","$ratings.1"]},true,false]}}}, 
     {$match:{"isGreater": true}}]); 
> 

> db.test.find({$where: "this.ratings.0" < "this.ratings.1"}); 
Error: error: { 
    "ok" : 0, 
    "errmsg" : "$where got bad type", 
    "code" : 2, 
    "codeName" : "BadValue" 
} 

db.test.find({ "ratings.0":{ "$のGT": "ratings.1"}}この記事のために私は再び次のように実行しました);私は評価して、正しい配列のインデックスを使用してい

証明#:。

> db.test.find({"ratings.0":5}); 
{ "_id" : ObjectId("5887a9202d599801b7df2c3c"), "name" : "soccer66", "ratings" : [ 5, 3.2, 1 ] } 
> 

答えて

2

Do not use the $where operator.

これには集約フレームワークを使用する必要があります。

db.test.aggregate([ 
    { "$match": { "ratings.1": { "$exists": true } } }, 
    { "$redact": { 
     "$cond": [ 
      { "$gt": [ 
       { "$arrayElemAt": [ "$ratings", 0 ] }, 
       { "$arrayElemAt": [ "$ratings", 1 ] } 
      ]}, 
      "$$KEEP", 
      "$$PRUNE" 
     ] 
    }} 
]) 
+0

パーフェクト、ありがとうStyvane!あなたのリンクの推論を通してこれを受け入れました。 –

2

あなた$where声明の中で "どこで" 述語は引用符で囲む必要があります全体:

db.test.find({$where: "this.ratings[0] < this.ratings[1]"}); 
+0

ありがとうございました!超高速の応答と簡潔さのためにアップフォーノートされています(最適なハハではないかもしれませんが)。 –