以下是我的mongodb集合中的文档示例:
{
"_id" : ObjectId("561e0de61c9218b7bf9877c3"),
"Date" : NumberLong(20151014),
"Hour" : NumberLong(10),
"ProductId" : ObjectId("5614ba9c2e131caa098b4567"),
"ProductName" : "Test",
"ProducerId" : ObjectId("5617802151f8adf4db329d52"),
"ProducerName" : "Producer",
"ProducerRate" : NumberLong(300),
"ProducerMedium" : "Emailer",
"TotalLead" : NumberLong(6),
"VerifiedLead" : NumberLong(3),
"UnverifiedLead" : NumberLong(2),
"UnQualifiedLead" : NumberLong(1),
"TotalEarning" : NumberLong(660),
"Consumers" : [
{
"ConsumerId" : ObjectId("5617802151f8adf4db329d54"),
"ConsumerName" : "Consumer1",
"ConsumedRate" : NumberLong(120),
"ConsumedLead" : NumberLong(3),
"Earning" : NumberLong(360)
},
{
"ConsumerId" : ObjectId("5617802151f8adf4db329d58"),
"ConsumerName" : "Consumer2",
"ConsumedRate" : NumberLong(100),
"ConsumedLead" : NumberLong(3),
"Earning" : NumberLong(300)
}
]
}
现在我想从php中的数据库中获取ConsumerId和ProductId的ConsumedLead。
我到目前为止所做的是给我TotalLead和VerifiedLead按产品ID分组,但不知道如何获得基于消费者的结果:
$keyf = new MongoCode('function(doc) {
return {\'ProductId\': doc.ProductId,\'ProductName\': doc.ProductName};
}');
$initial = array('TotalLead'=>0,'VerifiedLead'=>0);
$reduce = "function(obj, prev) {
prev.TotalLead += obj.TotalLead;
prev.VerifiedLead += obj.VerifiedLead;
}";
$result = $collection->group($keyf, $initial, $reduce);
var_dump($result);
请帮助。
编辑: 预期结果wpuld是:
{ [0]=> array(4) { ["ProductId"]=> object(MongoId)#8 (1) { ["$id"]=> string(24) "5614ba9c2e131caa098b4567" } ["ProductName"]=> string(4) "Test" ["ConsumerId"]=> object(MongoId)#8 (1) { ["$id"]=> string(24) "5617802151f8adf4db329d58" } ["ConsumedLead"]=> float(4) } }
答案 0 :(得分:1)
解决方案是使用 aggregation framework ,其中操作包含 $unwind
运算符初始管道阶段,因为这将解构{{1输入文档中的数组字段,并为每个元素输出一个文档。每个输出文档都使用元素值替换数组。这样, $sum
步骤中的 $group
组累加器运算符就可以工作,从而为您提供所需的{{1}按Consumers
和ConsumedLead
分组:
ConsumerId
对上面的示例运行此聚合操作将导致:
ProductId
所以你最后的工作 aggregation in PHP 应该是:
db.collection.aggregate([
{
"$unwind": "$Consumers"
},
{
"$group": {
"_id": {
"ProductId": "$ProductId",
"ConsumerId": "$Consumers.ConsumerId"
},
"TotalConsumedLead": {
"$sum": "$Consumers.ConsumedLead"
}
}
}
])