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

问题描述

从记录数组过滤项目它应该只返回两个项目,因为records.score = 100 只有两个项目,而不是它返回我所有的记录。你能帮忙解决这个问题吗?

我有多个记录,其中我只想获取过滤记录。我做错的地方请指导和建议。

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

解决方法

试试这个

$command = new MongoDB\Driver\Command([ '聚合' => '集合',

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

]);

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...