使用 php 从嵌入式数组中获取记录来编写 mongodb 驱动程序查询

write mongodb driver query with php fetch records from embedded array

从记录数组中过滤项目它应该只有 return 两个项目,因为 records.score = 100 只有两个项目而不是它 return 我所有的记录。能否请您帮忙解决这个问题。谢谢。

我有多个记录,其中我只想获取过滤记录。有哪里做错了请指教指教

stdClass Object
(
    [_id] => e5s65d5e5s65d5s65d44f12
    [records] => Array
        (
            [0] => stdClass Object
                (
                    [date] => MongoDB\BSON\UTCDateTime Object
                        (
                            [milliseconds] => 1609923848000
                        )

                    [score] => 100
                    [country] => US
                    [state] => Connecticut
                    [city] => Berlin
                    
                )

            [1] => stdClass Object
                (
                    [date] => MongoDB\BSON\UTCDateTime Object
                        (
                            [milliseconds] => 1609923501000
                        )

                    [score] => 100
                    [country] => US
                    [state] => California
                    [city] => Barstow
                    
                )

            [2] => stdClass Object
                (
                    [date] => MongoDB\BSON\UTCDateTime Object
                        (
                            [milliseconds] => 1609923157000
                        )

                    [score] => 145
                    [country] => US
                    [state] => Alabama
                    [city] => Alexander City
                    
                )

            [3] => stdClass Object
                (
                    [date] => MongoDB\BSON\UTCDateTime Object
                        (
                            [milliseconds] => 1609923108000
                        )

                    [score] => 150
                    [country] => US
                    [state] => Alaska
                    [city] => Anchorage
                    
                )

        )

)


$mng = new MongoDB\Driver\Manager("mongoatlas/");
$filter = ['records.score' => '100'];

$query = new MongoDB\Driver\Query($filter, ['sort' => ['records.date' => 1], 'limit' => 6]);

$rows = $mng->executeQuery("db.table", $query);

预期结果应该只有两个州为加利福尼亚州康涅狄格州的项目,因为他们的分数是 100

试试这个

$命令=新MongoDB\Driver\Command([ 'aggregate' => 'collection',

'pipeline' => [
    ['$unwind' => '$records'],
    ['$match' => ['records.score' => '100']],
    ['$sort' => ['records.date' => 1]],
    ['$limit' => 6]
],
'cursor' => new stdClass,

]);

$cursor = $mng->executeCommand('database', $command);