为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
白猪掌柜的 2022-08-19 10:59:37
我正在使用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) 获取移动来过滤所有这些“移动”字段?
查看完整描述

1 回答

?
慕容森

TA贡献1853条经验 获得超18个赞

好吧,所以我想通了。我只需要使用聚合管道。


下面是给出预期输出的 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);


查看完整回答
反对 回复 2022-08-19
  • 1 回答
  • 0 关注
  • 73 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信