简体   繁体   English

Mongo聚合查询不能用作PHP Mongo查询

[英]Mongo Aggregate Query Not Functioning as PHP Mongo Query

I have the following Mongo Aggregate query: 我有以下Mongo Aggregate查询:

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}
        }
    }
)

Which I am attempting to turn into a PHP Mongo Query as so: 我正试图将其转换为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)
        )
    )
);

Without the last match, this query works in PHP. 如果没有最后一个匹配项,此查询将在PHP中运行。 However the final match works in the Mongo query at the top, so I feel I have missed something in the PHP query. 但是最终匹配在顶部的Mongo查询中有效,因此我觉得我在PHP查询中错过了一些东西。 The error I am getting currently is exception: pipeline element 0 is not an object' 我当前遇到的错误是异常:管道元素0不是对象'

I can't tell if this is the only error -- but your array s are not properly nested: 我无法确定这是否是唯一的错误-但您的array未正确嵌套:

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

Should be: 应该:

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

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

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