在PHP中由mongodb聚合Cursor返回的空集

时间:2015-06-19 12:43:35

标签: php mongodb mongodb-query pymongo

MongoDB聚合查询返回空集.Below是我在php脚本中使用的查询,用于从mongoDB中检索数据。请让我知道我哪里出错了。

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

如果我在mongoDB shell中运行相同的查询,则会按预期显示输出。

  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 }

集合中的示例数据:

{
        "_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 个答案:

答案 0 :(得分:1)

尝试生成 MongoDate() 对象,如下所示

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

然后您可以在汇总管道中使用它,而不是PHP查询中的MongoDB ISODate对象。

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