2

试图将我的游戏迁移到 mongodb (linux-i686-2.4.6) 但到目前为止有很多困难:( 一个就是那个;我有一个名为 gamesTable 的集合,其中包含以下元素,我想在 playerHistories 中进行搜索大批。

{
"_id": {
    "$oid": "52307b8fe4b0fc612dea2c70"
},
"id": "52307b8fe4b0fc612dea2c70", "name": "poker", "initTime": 1378909071070, "startTime": 1378909071098, "endTime": 1378909071134,
"playerHistories": [
    {
        "playerId": "52307b8fe4b0fc612dea2c6e",
        "time": 1378909071098,
        "event": "EnteredGame"
    } ,
    {
        "playerId": "52307b8fe4b0fc612dea2c6f",
        "time": 1378909071098,
        "event": "EnteredGame"
    } ,
    {
        "playerId": "52307b8fe4b0fc612dea2c6f",
        "time": 1378909071117,
        "event": "LostGame"
    } ,
    {
        "playerId": "52307b8fe4b0fc612dea2c6e",
        "time": 1378909071128,
        "event": "WonGame"
    }
]
},
{
"_id": {
    "$oid": "52307b8fe4b0fc612dea2c71"
}, "id": "52307b8fe4b0fc612dea2c71", "name": "poker", "initTime": 1378909071150, "startTime": 1378909071165, "endTime": 1378909071189,
"playerHistories": [
    {
        "playerId": "52307b8fe4b0fc612dea2c6e",
        "time": 1378909071165,
        "event": "EnteredGame"
    } ,
    {
        "playerId": "52307b8fe4b0fc612dea2c6f",
        "time": 1378909071165,
        "event": "EnteredGame"
    } ,
    {
        "playerId": "52307b8fe4b0fc612dea2c6e",
        "time": 1378909071176,
        "event": "LostGame"
    } ,
    {
        "playerId": "52307b8fe4b0fc612dea2c6f",
        "time": 1378909071183,
        "event": "WonGame"
    }
]
}

我想找到一个玩家赢得的比赛,在我们的例子中是;

{ "playerHistories.playerId" : "52307b8fe4b0fc612dea2c6f" , "playerHistories.event" : "WonGame"}}

我读到我应该使用 $elemMatch 来匹配数组中的元素但是它什么都不返回:(

这是我使用的代码

    BasicDBObject elemMatch = new BasicDBObject();
    elemMatch.put("playerHistories.playerId", player1.getId());
    elemMatch.put("playerHistories.event", "WonGame");
    BasicDBObject foo = new BasicDBObject();
    foo.put("$elemMatch", elemMatch);
    gamesTable.find(foo);

我究竟做错了什么?

4

2 回答 2

5

感谢parvin,我发现它改变了他的解决方案。

    DBObject statusQuery = new BasicDBObject("event", "WonGame");
    statusQuery.put("playerId", "52307b8fe4b0fc612dea2c6f");
    DBObject fields = new BasicDBObject("$elemMatch", statusQuery);
    DBObject query = new BasicDBObject("playerHistories",fields);
    gamesTable.find(query);
于 2013-09-12T07:57:10.973 回答
2

你可以这样做:

        DBObject query = new BasicDBObject("playerHistories.playerId", "52307b8fe4b0fc612dea2c6f");

        DBObject statusQuery = new BasicDBObject("event", "WonGame");
        DBObject elemMatchQuery = new BasicDBObject("$elemMatch", statusQuery);

        DBObject fields = new BasicDBObject();
        fields.put("playerHistories", elemMatchQuery);
        fields.put("initTime", 1);
        fields.put("startTime", 1);
        fields.put("endTime", 1);

        DBCursor cur = coll.find(query, fields);
于 2013-09-11T14:48:15.917 回答