【问题标题】:Query document's array fields in PHP MongoDB using filter and options使用过滤器和选项在 PHP MongoDB 中查询文档的数组字段
【发布时间】:2020-01-25 18:28:18
【问题描述】:

我正在使用 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 的板。然后我想搜索所有这些棋盘的“moves”字段,我想要那个“moves”字段的 min(_id)。

我目前有这个查询:

$filter = ['player' => '93'];
$options = [
    'projection' => ['_id' => 0,
                     'moves' => 1]
];
$query = new MongoDB\Driver\Query($filter, $options);

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

然后我怎样才能通过仅使用 min(_id) 获取移动来过滤所有这些“移动”字段?

【问题讨论】:

    标签: php mongodb mongodb-query nosql


    【解决方案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' }
           }    
        }
    ])
    

    下面是使用 Command 和聚合对应的 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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-08
      • 1970-01-01
      • 2019-07-11
      相关资源
      最近更新 更多