简体   繁体   English

带有嵌套对象的文档中的mongodb php查询

[英]mongodb php query in documents with nested objects

So here is a sample of a document in my mongodb collection: 因此,这是我的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)
        }
    ]
}

Now i want to get the ConsumedLead grouped by ConsumerId and ProductId from the database in php. 现在,我想从php的数据库中按ConsumerId和ProductId分组来使用ConsumedLead。

what i have did so far to give me TotalLead and VerifiedLead grouped by product id but have no idea how to get consumerbased results for same: 到目前为止,我所做的是按照产品ID将TotalLead和VerifiedLead归类给我,但不知道如何获得基于消费者的结果:

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

Any Help Please. 任何帮助,请。

EDIT: expected result wpuld be : 编辑:预期结果将是:

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

The solution is to use the aggregation framework where the operation includes an $unwind operator initial pipeline stage as this will deconstruct the Consumers array field from the input documents and outputs a document for each element. 解决方案是使用聚合框架 ,其中的操作包括$unwind运算符的初始管道阶段,因为这将从输入文档中解构Consumers数组字段,并为每个元素输出一个文档。 Each output document replaces the array with an element value. 每个输出文档用元素值替换数组。 This will then make it possible for the $sum group accumulator operator in the $group step to work and thus givies you the required ConsumedLead grouped by ConsumerId and ProductId : 于是,这将有可能为$sum在组蓄电池操作$group步工作,从而givies你所需要的ConsumedLead通过分组ConsumerIdProductId

db.collection.aggregate([
    {
        "$unwind": "$Consumers"
    },
    {
        "$group": {
            "_id": {
                "ProductId": "$ProductId",
                "ConsumerId": "$Consumers.ConsumerId"
            },
            "TotalConsumedLead": {
                "$sum": "$Consumers.ConsumedLead"
            }
        }
    }
])

Running this aggregation operation on the above sample will result: 对以上示例运行此聚合操作将导致:

/* 0 */
{
    "result" : [ 
        {
            "_id" : {
                "ProductId" : ObjectId("5614ba9c2e131caa098b4567"),
                "ConsumerId" : ObjectId("5617802151f8adf4db329d58")
            },
            "TotalConsumedLead" : NumberLong(3)
        }, 
        {
            "_id" : {
                "ProductId" : ObjectId("5614ba9c2e131caa098b4567"),
                "ConsumerId" : ObjectId("5617802151f8adf4db329d54")
            },
            "TotalConsumedLead" : NumberLong(3)
        }
    ],
    "ok" : 1
}

So your final working aggregation in PHP should be: 因此,您在PHP中的最终工作汇总应该是:

$pipeline = array(    
    array('$unwind' => '$Consumers'),
    array(
        '$group' => array(
            '_id' => array(
                'ProductId' => '$ProductId',
                'ConsumerId' => '$Consumers.ConsumerId',
            ),
            'TotalConsumedLead' => array(
                '$sum' => '$Consumers.ConsumedLead'
            ),
        )
    ),
);

$out = $collection->aggregate($pipeline ,$options);

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

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