MongoDB查询排序计数

时间:2013-03-23 10:40:58

标签: mongodb bson

您好我有2个游戏记录:

游戏1 ,其中包含玩家列表p1( alice ),p2( bob ),p3( matt ),p4( tom

游戏2 ,其中包含玩家列表p1( alice ),p2( bob ),p3( jack ),p4( tom

我想查询我的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;

使用mongo我尝试的是:

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

有人可以帮我修复MongoDB的查询吗? 谢谢

修改

我认为我越来越接近我想要的,但仍然是错误的查询:

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

请提出解决方案。感谢

编辑2

游戏文档的一个例子:

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

1 个答案:

答案 0 :(得分: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运营商可能更简单