在 Jessengers MongoDB 中使用 Laravel Lumen 中的聚合函数
Posted
技术标签:
【中文标题】在 Jessengers MongoDB 中使用 Laravel Lumen 中的聚合函数【英文标题】:use of aggregate function in Laravel Lumen with Jessengers MongoDB 【发布时间】:2021-02-23 12:41:40 【问题描述】:我有以下收藏:
[
"_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
]
我想根据每个“原因”计算每个“employ_id”的分数。例如,employ_id 对原因电子邮件的得分:3600 和对 facebook:1000
我正在使用 Laravel Lumen 和 Jessengers MongoDb 库。
这是我的代码:
Model::groupBy('employ_id')-get('reason','score');
【问题讨论】:
【参考方案1】:虽然可能有点晚了,但我希望它有所帮助, 据我了解,这是您可以在mongodb中执行的操作,
db.getCollection('yourcolection').aggregate([
$group :
_id : employ_id:"$employ_id", reason:"$reason",
count:
$sum:"$score"
])
它会回报你,
/* 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
在模型中使用 Jenssegers mongodb for Laravel,
$result = DB::collection('yourcollection')->raw(function($collection)
return $collection->aggregate([
[ '$group' => [
'_id' => [
'employ_id'=>"$employ_id",
'reason'=>"$reason"
],
'count' => [
'$sum' => "$score"
]
]
]
]);
);
【讨论】:
以上是关于在 Jessengers MongoDB 中使用 Laravel Lumen 中的聚合函数的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 Spring Boot 在 Mongodb 中保存重复项?