2017-02-10 87 views
1

我在產品集合中有以下文檔。使用elemMatch從MongoDB中的數組獲取數據

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的做精確匹配。這意味着不應該有任何附加屬性,基本上你的情況,預計分數爲{「$情商」:5}(字面上有一個名爲$ EQ屬性)

欲瞭解更多信息請查看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 
             } 
            } 
           } 
          }