2017-10-15 45 views
1

我有這樣的要求,在那裏我有如下的集合:最高值

{ 
     "_id" : 1, 
     "name" : "sam", 
     "Array" : [ 
      { "K" : "A", "V" : 8 }, 
      { "K" : "B", "V" : 5 }, 
      { "K" : "C", "V" : 13 } 
     ] 
}, 
{ 
    "_id" : 2, 
    "name" : "tom", 
    "Array" : [ 
     { "K" : "D", "V" : 12 }, 
     { "K" : "E", "V" : 14 }, 
     { "K" : "F", "V" : 2 } 
    ] 
}, 
{ 
    "_id" : 3, 
    "name" : "jim", 
    "Array" : [ 
     { "K" : "G", "V" : 9 }, 
     { "K" : "H", "V" : 4 }, 
     { "K" : "I", "V" : 2 } 
    ] 
} 

我想運行具有最高返回每個_id的子文檔查詢「V」,所以在這種情況下,我會得到:

{ "_id" : 1, "name" : "sam", "Array" : [ { "K" : "C", "V" : 13 } ] } 
{ "_id" : 2, "name" : "tom", "Array" : [ { "K" : "E", "V" : 14 } ] } 
{ "_id" : 3, "name" : "jim", "Array" : [ { "K" : "G", "V" : 9 } ] } 

回答

0

您可以使用其中V字段的值等於使用$filter數組中的最大值和$max運營商只能選擇子文檔。

這裏使用$addFields管道階段來指定文檔中的所有其他字段。

db.collection.aggregate([ 
    { 
     "$addFields":{ 
     "Array":{ 
      "$filter":{ 
       "input":"$Array", 
       "cond":{ 
        "$eq":[ 
        "$$this.V", 
        { 
         "$max":"$Array.V" 
        } 
        ] 
       } 
      } 
     } 
     } 
    } 
])