0

I have the following structure and data:

game{
    alias: "GAME01",
    players[
        {
            name: Nick,
            city: London
        },
        {
            name: Chris,
            city: London
        },
        {
            name: Emmy,
            city: Paris
        }
    ]
}

and I need to get an array just with the players from London. Something like:

[[name: Nick, city: London], [name: Chris, city: London]]

How can I get it? Any ideas?

All I've tryed returns me the entire game, or an empty object.

mongoDB version: 3.4.4 / mongoDB driver version 1.6.14

Thanks!

What I've tryed:

Try 1:

$game = $mongo->game->find(
    array("alias" => "GAME01", "players.city" => "London"),
    array('_id' => false, "players" => array('$elementMatch' =>
    array("players.city" => "London")))
);

Returns:

object(MongoCursor)#10 (0) {}

Try 2:

$game = $mongo->game->find(
    array("alias" => "GAME01", 
    array("players" => array('$elementMatch' => array("city" => "London"))))
);

Returns:

object(MongoCursor)#10 (0) {}

Try 3:

$ops = array(
    array('$match' => array("alias" => "GAME01")),
    array('$project' => array("game.players" => 1)),
    array('$unwind' => '$players'),
    array('$match' => array("players.city" => "London")),
    array('$group' => array(
        '_id' => '$_id',
        'players' => array(
            '$push' => '$players'))
    )
);

$game = $mongo->game->aggregate($ops);

Returns:

array(2) {
    ["result"] => array(0) {}
    ["ok"] => float(1)
}
Nat
  • 1
  • 1
  • put what had you tried – hassan May 28 '17 at 13:07
  • Thanks Hassan, it's my first time here. I've added my tries. – Nat May 30 '17 at 21:59
  • You should update your first match to `array('$match' => array("game.alias" => "GAME01")),` and change your project to `array('$project' => array("players" => '$game.players')),`. You can alternatively use `$filter`. More here https://stackoverflow.com/questions/15117030/how-to-filter-array-in-subdocument-with-mongodb – s7vr May 30 '17 at 22:11

1 Answers1

0

Thanks! I finally found this solution:

$ops = array(
    array('$match' => array(
        "alias" => "GAME01",
        )
    ),
    array('$project' => array(
        "players" => 1
        )
    ),
    array('$unwind' => '$players'),
    array('$match' => array(
            "athletes.city" => "London"
            )
        ),
    array('$group' => array(
            '_id' => '$_id',
            'players' => array(
            '$push' => '$players'
            )
        )
    )
);

$game = $mongo->game->aggregate($ops);
$players = $game["result"][0]["players"];
Nat
  • 1
  • 1