2013-07-08 101 views
0

我的mongoDB集合中包含以下文檔。包含數組的文檔的MongoDB組

{ 
    "_id" : ObjectId("51d90c3746503d6ab5933b88"), 
    "scorearray" : [ 
    { 
     "score" : 0.0 
    }, 
    { 
     "score" : 7.0 
    } 
    ], 
    "player" : "Arod" 
} 

/* 1 */ 
{ 
    "_id" : ObjectId("51d90c0d46503d6ab5933b86"), 
    "scorearray" : [ 
    { 
     "score" : 2.0 
    }, 
    { 
     "score" : 1.0 
    }, 
    { 
     "score" : 5.0 
    }], 
    "player" : "Martini" 
} 

我試圖讓每個球員的最高分,我有一個查詢,如下,但它給了我只是一個球員,即AROD 7.0,我既需要AROD 7.0馬爾蒂尼5.0在我的查詢結果。

有人可以請指導我如何修改下面的查詢。任何指導將不勝感激。

db.playerscorecollection.aggregate([ 
    {$project:{_id:0,player:1, "scorearray.score":1}}, 
    {$unwind:"$scorearray"}, 
    {$sort:{"scorearray.score":-1}}, 
    {$limit:1} 
]); 

回答

2

你可以使用$最大運營商在聚集:

db.playerscorecollection.aggregate([ 
{ $unwind: "$scorearray"}, 
{ $group: { _id: "$player", maxScore: { $max: "$scorearray.score" } } } 
]) 

-----關於第二個問題找到每個玩家的最高分,並在其中是最高分發生的地點:

db.playerscorecollection.aggregate(
     { $unwind: "$scorearray"}, 
     { $group: { _id: { player: "$player", venue: "$scorearray.venue", score: "$scorearray.score" } } }, 
     { $sort: { "_id.score" : 1 } }, 
     { $group: { _id: "$_id.player", maxScore: { $last: "$_id.score" }, venue: { $last: "$_id.venue"} } } 
) 
+0

感謝您的出色答卷,我才意識到,我需要venuealso添加到陣列的得分,如果我需要得到球員和場地的比賽在也打出了最高分是什麼? – user1965449

+0

謝謝你的回答,我只是意識到我需要爲比分陣列添加場地,我需要獲得球員的最高分和比賽的場地嗎?我試圖爲該組添加場地,但是我收到一個錯誤,指出「組合場地'必須定義爲對象內部的表達式」。你能幫忙嗎? – user1965449

+0

謝謝你提出的第二個問題,我使用以下更簡單的方法實現它。現在,我需要指導將它轉換爲使用Java DB驅動程序檢索數據的Java程序。任何指導將非常感激。 db.playerscorecollection.aggregate {[$ unwind:「$ scorearray」}, {$ group:{_id:{player:'$ player,venue:'$ venue'},maxScore:{$ max:「$ scorearray .score「}}} ]); – user1965449

0

謝謝你的第二個問題,我用以下更簡單的方法取得了它。

現在我需要指導將它轉換爲使用Java DB驅動程序檢索數據的Java程序。任何指導將非常感激。

db.playerscorecollection.aggregate([ 
{ $unwind: "$scorearray"}, 
{ $group: { _id: {player:'$player,venue:'$venue'}, 
maxScore: { $max: "$scorearray.score" } } } ]); 
相關問題