Null set returned by mongodb aggregate Cursor in PHP

1.1k Views Asked by At

MongoDB aggregate query returning empty set .Below is the query i am using in a php script to retrieve data from mongoDB .Please let me know where i am going wrong.

  $result = $collection->aggregateCursor([[ '$match'=> [ 'date'=> [ '$gte'=>ISODate("2015-06-01T00:00:00Z"), '$lte'=>ISODate("2015-06-03T00:00:00Z")] ] ],[ '$group'=> [ '_id'=> '$date', 'count'=> [ '$sum'=>1 ] ] ]]);

If i run same query in mongoDB shell.it is showing the output as expected.

  db.mnumber.aggregate([{ $match: { date: { $gte:new ISODate("2015-06-01T00:00:00Z"), $lte:new ISODate("2015-06-03T00:00:00Z") } } },{ $group: { _id: "$date", 'count': { $sum:1 } } }])
    { "_id" : ISODate("2015-06-01T00:00:00Z"), "count" : 10000 }
    { "_id" : ISODate("2015-06-02T00:00:00Z"), "count" : 10000 }
    { "_id" : ISODate("2015-06-03T00:00:00Z"), "count" : 10000 }

Sample data in collection:

{
        "_id" : ObjectId("55743941789a9abe7f4af3fd"),
        "msisdn" : "1234567890",
        "act_date" : ISODate("2014-11-24T00:00:00Z"),
        "date" : ISODate("2015-06-07T00:00:00Z"),
        "recharge_stats" : {
                "recharge_amt" : 0,
                "rechargetype" : "WEB"
        },
        "voice_usage" : {
                "local_og_mou" : 20,
                "local_other_mobile_og_mou" : 0,
                "nld_og_mou" : 0,
                "nld_other_mobile_og_mou" : 10
        },
        "gprs_usage" : {
                "total_access_count" : 1,
                "total_datavolume_mb" : 42
        },
        "sms_usage" : {
                "freesms" : 3,
                "local_sms_count" : 0,
                "nat_sms_count" : 0,
                "inter_sms_count" : 0
        },
        "campaign_details" : {
                "camp_id" : "M01124",
                "message" : "Hello .",
                "msg_id" : "9174051951412054925609431100",
                "cmp_activation_status" : "YES"
        }
}
1

There are 1 best solutions below

3
On BEST ANSWER

Try to generate a MongoDate() object as follows

$dateFrom = new MongoDate(strtotime("2015-06-01T00:00:00Z"));
$dateTo = new MongoDate(strtotime("2015-06-03T00:00:00Z"));

which you can then use in your aggregation pipeline instead of the MongoDB ISODate objects in your PHP query.

/* Run the command cursor */
$result = $collection->aggregateCursor(
    [
        [ '$match' => [ 'date'=> [ '$gte' => $dateFrom, '$lte' =>  $dateTo ]  ] ],
        [ '$group' => [ '_id' => '$date', 'count' => [ '$sum' => 1 ] ] ]            
    ]        
);