2016-06-06 43 views
2

我喜歡這個查找文件包含一個特定的值

{ "_id" : ObjectId("5755d81e2935fe65f5d167aa"), "prices" : [ 23, 11, 2, 3, 4, 1, 232 ] }, 
{ "_id" : ObjectId("5755d81e2935fe65f5d167ab"), "prices" : [ 99, 3, 23, 23, 12 ] }, 
{ "_id" : ObjectId("5755d81e2935fe65f5d167ac"), "prices" : [ 999, 12, 3, 4, 4, 4, 4, 4, 123 ] }, 
{ "_id" : ObjectId("5755d81e2935fe65f5d167ad"), "prices" : [ 24, 3, 4, 5, 6, 7, 723 ] } 

文檔的最大occurence陣列,我想找到陣「價格」含有在數字4的最高金額,文件我的情況是第三個文件。有什麼方法可以查詢它嗎?

+0

使用此答案爲例如:http://stackoverflow.com/questions/20850824/how-to-count-occurrences-in-nested-document-in-mongodb –

+0

這一個,以及:HTTP:/ /stackoverflow.com/questions/14319616/how-to-count-occurence-of-each-value-in-array –

+0

類似於'db.prices.aggregate([{$ unwind:「$ prices」},{$ sort :{「prices」:-1}},{$ limit:1}])''可以幫助 –

回答

2

從MongoDB的3.2開始,我們可以$project我們的文件,並使用$size$filter運營商每個數組中返回數4的「計數」。從那裏我們需要$group使用該「值」,並使用累加器運算符來返回具有相同「最大值」的文檔數組。接下來你你的文件由_id和使用$limit返回文檔的最大出現4

db.collection.aggregate(
    [ 
     { "$project": { 
      "prices": 1, 
      "counter": { 
       "$size": { 
        "$filter": { 
         "input": "$prices", 
         "as": "p", 
         "cond": { "$eq": [ "$$p", 4 ] } 
        } 
       } 
      } 
     }}, 
     { "$group": { 
      "_id": "$counter", 
      "docs": { "$push": "$$ROOT" } 
     }}, 
     { "$sort": { "_id": -1 } }, 
     { "$limit": 1 } 
    ] 
) 
相關問題