Reputation: 61
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');
Upvotes: 0
Views: 404
Reputation: 3420
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"
]
]
]
]);
});
Upvotes: 0