Trying to migrate my game to mongodb (linux-i686-2.4.6) but so far having a lot of struggle :( one is that; I have a collection named gamesTable with the following elements below and I want to make a search in playerHistories array.
{
"_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"
}
]
}
and I want to find games won by a player, in our example it is;
{ "playerHistories.playerId" : "52307b8fe4b0fc612dea2c6f" , "playerHistories.event" : "WonGame"}}
I read that I should use $elemMatch for matching elements in an array however it returns nothing :(
here is the code I use
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);
What am I doing wrong?