【问题标题】:Mongo Aggregate Query Not Functioning as PHP Mongo QueryMongo 聚合查询不能作为 PHP Mongo 查询运行
【发布时间】:2015-05-31 01:58:44
【问题描述】:

我有以下 Mongo 聚合查询:

db.getCollection('datas').aggregate(
    {
        "$match":{
            "payload.category_ids":ObjectId("5502b04bee60fc1ed06e2fa4"),
            "time":{ "$gte":new Date(2015,4,22) }
        }
    },
    {
        "$group":{
            _id: "$user_id", 
            num_use: {"$sum":1}
        }
    },
    {
        "$sort":{"num_use":-1}
    },
    {
        "$match": {
            'num_use':{"$gte":10}
        }
    }
)

我正试图将其转换为 PHP Mongo 查询:

$topUserCat = $datas->aggregate(
    array(
        array('$match'=>
            array(
                'payload.category_ids'=>new MongoId($category_id),
                'time'=>array('$gte'=>new MongoDate(strtotime('-1 week')))
            )
        )
    ),
    array(
        '$group'=>array(
            '_id'=>'$user_id',
            'num_use'=>array('$sum'=>1)
        )
    ),
    array(
        '$match'=>array(
            "num_use"=>array('$gte'=>10)
        )
    )
);

没有最后一个匹配项,此查询在 PHP 中有效。然而,最终匹配在顶部的 Mongo 查询中有效,所以我觉得我在 PHP 查询中遗漏了一些东西。我目前得到的错误是异常:管道元素 0 不是对象'

【问题讨论】:

    标签: php mongodb


    【解决方案1】:

    我不知道这是否是唯一的错误——但您的 arrays 没有正确嵌套:

    $topUserCat = $datas->aggregate(
        array(   // <------------------- starts here
            array('$match'=>
                ...
            )
        ),       // <------------------- ends here
        array(
            '$group'=>
                ...
        ),
        array(
            '$match'=>
                ...
        )
    );
    

    应该是:

    $topUserCat = $datas->aggregate(
        array(   // <------------------- starts here
            array('$match'=>
                ...
            ),
            array(
                '$group'=>
                    ...
            ),
            array(
                '$match'=>
                    ...
            )
        )       // <------------------- ends here
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-19
      • 2015-03-20
      • 1970-01-01
      • 1970-01-01
      • 2019-05-06
      • 2017-05-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多