MongoDB + PHP:在文档中获取子数组

时间:2017-05-25 16:02:49

标签: php mongodb

我有以下结构和数据:

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

我需要与来自伦敦的玩家一起获得阵列。类似的东西:

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

我怎样才能得到它?有什么想法吗?

我试过的所有东西都让我回想起整个游戏,或者一个空洞的物体。

mongoDB版本:3.4.4 / mongoDB驱动版本1.6.14

谢谢!

我尝试过:

尝试1:

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

返回:

object(MongoCursor)#10 (0) {}

尝试2:

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

返回:

object(MongoCursor)#10 (0) {}

尝试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);

返回:

array(2) {
    ["result"] => array(0) {}
    ["ok"] => float(1)
}

1 个答案:

答案 0 :(得分:0)

谢谢!我终于找到了这个解决方案:

$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"];