简体   繁体   English

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

[英]Query document's array fields in PHP MongoDB using filter and options

I am using the PHP MongoDB\\Driver\\Manager and I want to query by creating a MongoDB\\Driver\\Query.我正在使用 PHP MongoDB\\Driver\\Manager,我想通过创建 MongoDB\\Driver\\Query 进行查询。

So I have the following collection design:所以我有以下集合设计:

{
    "_comment": "Board",
    "_id": "3",
    "player": "42",
    "moves": [{
        "_id": "1",
        "piece": "b3rw4",
        "from_pos": "E2",
        "to_pos": "E4"
    }]
}

How can i query this collection to receive, for all boards of a specific player all moves with min(id)?对于特定玩家的所有棋盘,我如何查询此集合以接收所有带有 min(id) 的移动? This means I first want to filter all boards, to get only boards with player ID.这意味着我首先要过滤所有板,以仅获取带有玩家 ID 的板。 Then I want to search all those board's "moves" fields, where I want the min(_id) of that "moves" field.然后我想搜索所有这些板的“移动”字段,我想要那个“移动”字段的 min(_id) 。

I currently have this query:我目前有这个查询:

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

This results in finding all "moves" arrays by Player 93.这导致玩家 93 找到所有“移动”数组。

How can I then filter all those "moves" fields by only getting the moves with min(_id)?我怎样才能通过只获取 min(_id) 的移动来过滤所有这些“移动”字段?

Ok, so I figured it out.好的,所以我想通了。 I simply had to use an aggregation pipeline.我只需要使用聚合管道。

Here is the shell command which gives the expected output:这是给出预期输出的 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' }
       }    
    }
])

Here is the corresponding PHP MongoDB code using Command and aggregate:这是使用命令和聚合的相应 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM