如何将下面的 MongoDB 查询转换为 PHP?

How to convert below MongoDB query into PHP?

以下查询在 Studio 3T 和 Robomongo 中运行良好,但我想将其转换为 PHP 格式,

以下是我的查询,

db.news.aggregate([
{
      $match: {  "_id" : "1" }
},
{
    "$project": {
        "comments": {
            "$filter": { 
                "input": "$comments",
                "as": "comment", 
                "cond": { "$eq": [ "$$comment.status", "active" ] } 
            }
        } 
    }
}, {
    "$project": {
        "comments": {
            "$slice": [
                {
                    "$slice": [
                        "$comments",
                        {
                            "$subtract": [ { "$size": [ "$comments" ] }, 1 ]
                        }
                    ]
                }, -1
            ]
        }
    }
}])

我试过下面,但它给出错误“Error: localhost:27017: FieldPath field names may not be empty strings.

PHP 转换样本:

<?php
        $commentsAggregate=array(
                            array('$match' => array("_id" => "1")),
                            array('$project' => array(
                                    "comments" => array(
                                        '$filter' => array(
                                            "input" => "$comments",
                                            "as" => "comment",
                                            "cond" =>  array('$eq' => array( "$$comment.status", 'active'))
                                    )))),
                            array('$project' => array(
                                "comments" => array(
                                '$slice' => array(array(
                                        '$slice' => array("$comments",array('$subtract' => array( array( '$size' => array("$comments")),1)))
                                        ), -1)
                                )))
                        );
$cursor=$collectionNews->aggregate($commentsAggregate);

请帮我转换上面的查询。

错误消息 "FieldPath field names may not be empty strings" 来自 the server。查看您提供的示例 PHP 代码,我注意到您不一致地使用单字符串和 double-quoted 字符串。特别是,这两个字符串脱颖而出:

  • "$$comment.status"
  • "$comment"

PHP 正在评估 double-quoted 字符串中的变量引用。假设局部范围实际上没有定义 $comment 变量,这些字符串将分别解析为 "$.status"""。正如 this script and execution output on 3v4l.org 中所证明的那样,这些示例应该 至少 导致未定义变量的 PHP 通知(我的本地 PHP 配置碰巧报告了这个在 "error" 级别)。如果您没有该错误消息的记录,我建议如下:

  • 检查您的 error_reporting 配置。
  • 理想情况下,您应该在开发环境中报告所有内容 (E_ALL)。完整的报告对于生产也是可取的,尽管在那里你可能想要禁用 display_errors(为了安全)并确保所有内容都被正确记录。
  • 如果发现错误 已被记录 ,请查看在调试此问题时是如何遗漏的。

至于根本原因,在PHP中写MongoDBqueries/commands时要注意使用single-quoted字符串。在 MongoCollection::find() documentation, but it's not something we repeat on every page, as PHP's double-quoted string evaluation 中有一个关于此的说明是驱动程序无法控制的。