2013-03-23 38 views
0

您好我有2個遊戲記錄:MongoDB的查詢分類數量

遊戲1與玩家P1(愛麗絲),P2(鮑勃),P3(亞光),P4的列表( 湯姆

遊戲2與玩家P1(愛麗絲),P2的列表(鮑勃),P3 (插孔),P4(湯姆

我想查詢我的MongoDB收集遊戲出現在同一場比賽爲BOB最經常的人分開。良好的效果在這種情況下將是:

Alice: appear 2 times 
Tom: appear 2 time 
Matt: appear 1 time 
Jack: appear 1 time 

在SQL我所做的:

   SELECT idplayer, COUNT(idplayer) AS countplayer 
      FROM (SELECT b.idgame, b.idplayer 
      FROM associations a, associations b 
      WHERE a.idplayer="BOB" 
      AND b.idgame=a.idgame 
      AND b.idplayer <> "BOB" 
      ORDER BY b.idgame DESC LIMIT 1000) as c 
      GROUP BY idplayer 
      ORDER BY countplayer DESC LIMIT 5; 

隨着蒙戈我想是這樣的:

gamesCollection.find("{playerid : #}","BOB").sort(//counter).limit(5)... 

有人可以幫我解決這個問題查詢MongoDB? 謝謝

編輯:

我想我越來越接近我想要的,但仍然是錯誤的查詢:

> db.games.aggregate("[{ $match: {playerid : 'bob'} }, {$group : { _id:null, cou 
nt: { $sum: 1}} } ]") 

請提出一個解決方案。感謝

EDIT 2

遊戲文件的一個例子:

{ "_id" : ObjectId("514d9afb6e058b8a806bdbc0"), "gameid" : 1, "numofplayers" : 3, 
"playersList" : [{"playerid" : "matt" },{"playerid" : "bob"},{"playerid" : "alice"} ] } 
+1

嘗試使用匯總框架:http://docs.mongodb.org/manual/reference/aggregation /。你可以在名稱上使用'$ match',在其他用戶上使用'$ group','$ sort'等。 – WiredPrairie 2013-03-23 11:51:07

回答

1

如果原文件是這樣的:

{ 
    _id: ObjectId(...), 
    players: [...] 
} 

然後,你可以使用aggregate做到這一點:

var playerId = 'bob'; 
db.records.aggregate([ 
    { $match: { players: playerId }}, 
    { $unwind: '$players' }, 
    { $match: { players: { $ne: playerId } } }, 
    { $group: { _id: { player: '$players' }, times: { $sum : 1} } }, 
    { $sort: { times: -1 } } 
]) 

UPD:

對於文檔:

{ 
    "_id" : ObjectId("514d9afb6e058b8a806bdbc0"), 
    "gameid" : 1, "numofplayers" : 3, 
    "playersList" : [ 
    {"playerid" : "matt" }, 
    {"playerid" : "bob"}, 
    {"playerid" : "alice"} 
    ] 
} 

查詢是:

var playerId = 'bob'; 
db.records.aggregate([ 
    { $match: { 'playersList.playerid': playerId }}, 
    { $unwind: '$playersList' }, 
    { $match: { 'playersList.playerid': { $ne: playerId } } }, 
    { $group: { _id: '$playersList.playerid', times: { $sum : 1} } }, 
    { $sort: { times: -1 } } 
]) 

//我還發現,$group運營商可以更簡單

+0

嗨,我不能解決如何用「... {_id:{player:'$ players'} ...」替換「player」與我的文檔的適當值。 一個遊戲看起來像這樣: { 「_id」:的ObjectId( 「514d9afb6e058b8a806bdbc0」), 「遊戲ID」:1, 「numofplayers」:3, 「playersList」:[{ 「playerid」: 「無光澤」}, {「playerid」:「bob」},{「playerid」:「alice」}]} 希望你能幫助我。謝謝 – nuvio 2013-03-23 13:51:47

+1

我在__update__中添加了答案 – user20140268 2013-03-23 14:24:20

+0

非常感謝,這真的很有幫助 – nuvio 2013-03-23 14:26:31