2017-02-10 11 views
1

製品コレクションには次のドキュメントがあります。MongoDBの配列からelemMatchを使用してデータを取得します

db.product.find() 
{ "_id" : 1, "results" : [ { "product" : "abc", "score" : 10 }, { "product" : "xyz", "score" : 5 } ] } 
{ "_id" : 2, "results" : [ { "product" : "abc", "score" : 8 }, { "product" : "xyz", "score" : 7 } ] } 
{ "_id" : 3, "results" : [ { "product" : "abc", "score" : 7 }, { "product" : "xyz", "score" : 8 } ] } 

次のクエリは、結果をelemMatchで期待どおりに返します。

> db.product.find( { results : { $elemMatch : { product : "xyz" , score : { $eq : 5} } } } ) 
{ "_id" : 1, "results" : [ { "product" : "abc", "score" : 10 }, { "product" : "xyz", "score" : 5 } ] } 

同様に、これも期待される結果を返します。

> db.product.find( { results : { product : "xyz" , score : 5 } } ) 
{ "_id" : 1, "results" : [ { "product" : "abc", "score" : 10 }, { "product" : "xyz", "score" : 5 } ] } 

しかし、比較演算子を配列内で使用すると、結果が得られません。

db.product.find( { results : { product : "xyz" , score : { $eq : 5} } } ) 

私はこの予期しない動作を把握することができません。

答えて

2

クエリを作成するには、サブ文書を渡す方法とドット表記を使用する方法があります。

ネストされたフィールドを照会するには、ドット表記を使用する必要があります。

db.test.find({"results.product": "xyz", "results.score": {$eq : 5}})

あなたがそうであるようにサブ文書を渡した場合、その後のMongoDBは完全一致を実行します。これは、あなたがする必要があることを意味します。これは、追加のプロパティが存在しないことを意味し、基本的にあなたのケースでは、スコアが{"$ eq":5}となることを期待しています

詳細については、this answerdocumentationを参照してください。

0

すべての4つのコマンドについて説明を実行しました。 mongoDBが内部で作成しているフィルタは次のとおりです。

db.product.find({ results : { product : "xyz" , score : 5 } }).explain() 
"filter" : { 
       "results" : { 
        "$eq" : { 
         "product" : "xyz", 
         "score" : 5 
        } 
       } 
      } 


db.product.find({ "results.product" : "xyz" , "results.score" : 5 }).explain() 
     "filter" : { 
        "$and" : [ 
         { 
          "results.product" : { 
           "$eq" : "xyz" 
          } 
         }, 
         { 
          "results.score" : { 
           "$eq" : 5 
          } 
         } 
        ] 
       } 

db.product.find( { results : { $elemMatch : { product : "xyz" , score : { $eq : 5} } } } ).explain() 
      "filter" : { 
         "results" : { 
          "$elemMatch" : { 
           "$and" : [ 
            { 
             "product" : { 
              "$eq" : "xyz" 
             } 
            }, 
            { 
             "score" : { 
              "$eq" : 5 
             } 
            } 
           ] 
          } 
        } 
       } 

db.product.find( { results : { product : "xyz" , score : { $eq : 5} } } ).explain() 

        "filter" : { 
           "results" : { 
            "$eq" : { 
             "product" : "xyz", 
             "score" : { 
              "$eq" : 5 
             } 
            } 
           } 
          } 
関連する問題