使用过滤器和选项在PHP MongoDB中查询文档的数组字段

我正在使用PHP MongoDB\Driver\Manager,我想通过创建MongoDB\Driver\Query进行查询。


所以我有以下的集合设计:


{

    "_comment": "Board",

    "_id": "3",

    "player": "42",

    "moves": [{

        "_id": "1",

        "piece": "b3rw4",

        "from_pos": "E2",

        "to_pos": "E4"

    }]

}

我如何查询此集合以接收,对于特定玩家的所有棋盘,所有移动都带有min(id)?这意味着我首先要过滤所有板,以便仅获取具有玩家ID的板。然后,我想搜索所有这些板的“移动”字段,我想要该“移动”字段的最小值(_id)。


我目前有这个查询:


$filter = ['player' => '93'];

$options = [

    'projection' => ['_id' => 0,

                     'moves' => 1]

];

$query = new MongoDB\Driver\Query($filter, $options);

这导致玩家93找到所有“移动”数组。


然后,如何通过仅使用 min(_id) 获取移动来过滤所有这些“移动”字段?


白猪掌柜的
浏览 74回答 1
1回答

慕容森

好吧,所以我想通了。我只需要使用聚合管道。下面是给出预期输出的 shell 命令:db.boards.aggregate( [    {     $match: {'player': '93'}    },    {     $unwind: {path: '$moves'}    },    {     $group:       {         _id: '$_id',         first_move: { $min: '$moves._id' },         from_pos : { $first: '$moves.from_pos' },         to_pos: { $first: '$moves.to_pos' }       }        }])以下是使用命令和聚合的相应PHP MongoDB代码:$command = new MongoDB\Driver\Command([    'aggregate' => 'boards',    'pipeline' => [        ['$match' => ['player' => '93']],        ['$unwind' => '$moves'],        ['$group' => ['_id' => '$_id',                      'firstMove' => ['$min' => '$moves._id'],                      'from_pos' => ['$first' => '$moves.from_pos'],                      'to_pos' => ['$first' => '$moves.to_pos']                     ]        ]    ],    'cursor' => new stdClass,]);$manager = new MongoDB\Driver\Manager($url);$cursor = $manager->executeCommand('db', $command);
打开App,查看更多内容
随时随地看视频慕课网APP