简体   繁体   中英

Mongo Aggregate Query Not Functioning as PHP Mongo Query

I have the following Mongo Aggregate query:

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:

$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. However the final match works in the Mongo query at the top, so I feel I have missed something in the PHP query. The error I am getting currently is exception: pipeline element 0 is not an object'

I can't tell if this is the only error -- but your array s are not properly nested:

$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
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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