简体   繁体   中英

use of aggregate function in Laravel Lumen with Jessengers MongoDB

I have the following collection:

[
   {
      "_id":"5fabdd45bf510000d7001430",
      "application_id":27,
      "employ_id":1,
      "reason":"email",
      "score":1800
   },
   {
      "_id":"5fabdd50bf510000d7001431",
      "application_id":28,
      "employ_id":1,
      "reason":"email",
      "score":1800
   },
   {
      "_id":"5fabdd5dbf510000d7001432",
      "application_id":28,
      "employ_id":2,
      "reason":"email",
      "score":1800
   },
   {
      "_id":"5fabdd68bf510000d7001433",
      "application_id":27,
      "employ_id":2,
      "reason":"email",
      "score":1800
   },
   {
      "_id":"5fabdd79bf510000d7001434",
      "application_id":27,
      "employ_id":2,
      "reason":"facebook",
      "score":1000
   },
   {
      "_id":"5fabdd84bf510000d7001435",
      "application_id":27,
      "employ_id":1,
      "reason":"facebook",
      "score":1000
   }
]

I want to calculate the score of each "employ_id" on the base of each "reason". for instance employ_id has score against reason email: 3600 and and against facebook: 1000

I am using Laravel Lumen and Jessengers MongoDb library.

here is my code:

Model::groupBy('employ_id')-get('reason','score');

though it might be quite a bit late, but I hope it helps, For what I have understood, here is what you can do in mongodb,

db.getCollection('yourcolection').aggregate([ 
                { $group : 
                    { _id : {employ_id:"$employ_id", reason:"$reason"},
                      count: { 
                                  $sum:"$score" 
                            }                  
                }}
            ])

It will return you,

/* 1 */
{
    "_id" : {
        "employ_id" : 1,
        "reason" : "facebook"
    },
    "count" : 1000
}

/* 2 */
{
    "_id" : {
        "employ_id" : 2,
        "reason" : "facebook"
    },
    "count" : 1000
}

/* 3 */
{
    "_id" : {
        "employ_id" : 2,
        "reason" : "email"
    },
    "count" : 3600
}

/* 4 */
{
    "_id" : {
        "employ_id" : 1,
        "reason" : "email"
    },
    "count" : 3600
}

writing that using Jenssegers mongodb for Laravel in model,

$result = DB::collection('yourcollection')->raw(function($collection)
{
    return $collection->aggregate([
        [    '$group' => [
                    '_id' => [
                            'employ_id'=>"$employ_id",
                            'reason'=>"$reason"
                        ],
                    'count' => [
                        '$sum' => "$score"
                    ]
            ]
        ]   
    ]);
});

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