[英]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".我想根据每个“原因”计算每个“employ_id”的分数。 for instance employ_id has score against reason email: 3600 and and against facebook: 1000
例如,employee_id 对原因电子邮件的得分:3600 和对 facebook:1000
I am using Laravel Lumen and Jessengers MongoDb library.我正在使用 Laravel Lumen 和 Jessengers MongoDb 库。
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,虽然可能有点晚了,但我希望它有所帮助,据我所知,这是您可以在 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,在模型中为 Laravel 使用 Jenssegers mongodb 写,
$result = DB::collection('yourcollection')->raw(function($collection)
{
return $collection->aggregate([
[ '$group' => [
'_id' => [
'employ_id'=>"$employ_id",
'reason'=>"$reason"
],
'count' => [
'$sum' => "$score"
]
]
]
]);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.